@gobing-ai/knowledge-kit 0.1.24 → 0.1.27

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 (77) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/dist/index.js +416 -79
  3. package/package.json +1 -1
  4. package/plugins/generations/episode-plan-gen/dist/index.js +47 -6
  5. package/plugins/generations/episode-plan-gen/src/index.ts +71 -7
  6. package/plugins/generations/music-gen/dist/index.js +17 -13
  7. package/plugins/generations/music-gen/src/audio/measure.ts +25 -20
  8. package/plugins/kk/decisions/extract/ai-news.yaml +8 -1
  9. package/plugins/kk/plugin.json +1 -1
  10. package/plugins/kk/publish-presets/daily-ai-voice.json +4 -4
  11. package/plugins/kk/publish-presets/itc-main.json +39 -23
  12. package/plugins/kk/scripts/cn-lead-gate.ts +494 -0
  13. package/plugins/kk/scripts/daily-stages.ts +880 -131
  14. package/plugins/kk/scripts/kk-workflow-stages.ts +58 -3
  15. package/plugins/kk/skills/content-safety/references/platforms/apple-podcasts.md +12 -5
  16. package/plugins/kk/skills/content-safety/references/platforms/wechatmp.md +8 -0
  17. package/plugins/kk/skills/content-safety/references/platforms/xiaoyuzhou.md +5 -0
  18. package/plugins/kk/skills/daily-news-cover/SKILL.md +96 -0
  19. package/plugins/kk/skills/daily-news-illustrations/SKILL.md +123 -0
  20. package/plugins/kk/skills/news-editorial/SKILL.md +25 -6
  21. package/plugins/kk/skills/news-editorial/references/daily-visual-composition.md +150 -0
  22. package/plugins/kk/skills/news-editorial/references/selection.md +42 -0
  23. package/plugins/kk/skills/news-editorial/references/style-contract.zh.md +1 -1
  24. package/plugins/kk/workflows/kk-article-generate.yaml +13 -1
  25. package/plugins/kk/workflows/kk-daily-ai-voice.yaml +6 -3
  26. package/plugins/kk/workflows/kk-daily-ai-voice2.yaml +6 -4
  27. package/plugins/kk/workflows/kk-news-generate.yaml +71 -1
  28. package/plugins/publishings/bilibili-pub/dist/index.js +35 -3
  29. package/plugins/publishings/bilibili-pub/dist/profile-check.js +35 -3
  30. package/plugins/publishings/cnblogs-pub/dist/index.js +35 -3
  31. package/plugins/publishings/cnblogs-pub/dist/profile-check.js +35 -3
  32. package/plugins/publishings/csdn-pub/dist/index.js +35 -3
  33. package/plugins/publishings/csdn-pub/dist/profile-check.js +35 -3
  34. package/plugins/publishings/infoq-pub/dist/index.js +35 -3
  35. package/plugins/publishings/infoq-pub/dist/profile-check.js +35 -3
  36. package/plugins/publishings/jike-pub/dist/index.js +35 -3
  37. package/plugins/publishings/jike-pub/dist/profile-check.js +35 -3
  38. package/plugins/publishings/juejin-pub/dist/index.js +35 -3
  39. package/plugins/publishings/juejin-pub/dist/profile-check.js +35 -3
  40. package/plugins/publishings/linkedin-pub/dist/index.js +86 -14
  41. package/plugins/publishings/linkedin-pub/dist/profile-check.js +52 -6
  42. package/plugins/publishings/linkedin-pub/src/index.ts +126 -9
  43. package/plugins/publishings/medium-pub/dist/index.js +9229 -279
  44. package/plugins/publishings/medium-pub/dist/profile-check.js +21205 -0
  45. package/plugins/publishings/medium-pub/package.json +3 -1
  46. package/plugins/publishings/medium-pub/plugin.json +6 -1
  47. package/plugins/publishings/medium-pub/src/browser-rail.ts +280 -0
  48. package/plugins/publishings/medium-pub/src/index.ts +17 -1
  49. package/plugins/publishings/medium-pub/src/profile-check.ts +27 -0
  50. package/plugins/publishings/shipinhao-pub/dist/index.js +38 -4
  51. package/plugins/publishings/shipinhao-pub/dist/profile-check.js +37 -4
  52. package/plugins/publishings/shipinhao-pub/src/flow.ts +5 -0
  53. package/plugins/publishings/shipinhao-pub/src/selectors.ts +11 -4
  54. package/plugins/publishings/sspai-pub/dist/index.js +35 -3
  55. package/plugins/publishings/sspai-pub/dist/profile-check.js +35 -3
  56. package/plugins/publishings/substack-pub/dist/index.js +35 -3
  57. package/plugins/publishings/substack-pub/dist/profile-check.js +35 -3
  58. package/plugins/publishings/surfdash-pub/dist/index.js +53 -15
  59. package/plugins/publishings/surfdash-pub/src/index.ts +31 -4
  60. package/plugins/publishings/surfdash-pub/src/patch.ts +81 -12
  61. package/plugins/publishings/threads-pub/dist/index.js +35 -3
  62. package/plugins/publishings/threads-pub/dist/profile-check.js +35 -3
  63. package/plugins/publishings/wechatmp-pub/dist/index.js +326 -44
  64. package/plugins/publishings/wechatmp-pub/dist/profile-check.js +69 -4
  65. package/plugins/publishings/wechatmp-pub/src/flow.ts +447 -53
  66. package/plugins/publishings/wechatmp-pub/src/index.ts +68 -2
  67. package/plugins/publishings/wechatmp-pub/src/page.ts +8 -0
  68. package/plugins/publishings/weibo-pub/dist/index.js +58 -9
  69. package/plugins/publishings/weibo-pub/dist/profile-check.js +57 -9
  70. package/plugins/publishings/weibo-pub/plugin.json +1 -1
  71. package/plugins/publishings/weibo-pub/src/index.ts +76 -8
  72. package/plugins/publishings/x-pub/dist/index.js +35 -3
  73. package/plugins/publishings/x-pub/dist/profile-check.js +35 -3
  74. package/plugins/publishings/xhs-pub/dist/index.js +35 -3
  75. package/plugins/publishings/xhs-pub/dist/profile-check.js +35 -3
  76. package/plugins/publishings/xiaoyuzhou-pub/dist/index.js +35 -3
  77. package/plugins/publishings/xiaoyuzhou-pub/dist/profile-check.js +35 -3
@@ -20219,7 +20219,12 @@ async function acquireProfileLease(profileDir, options = {}) {
20219
20219
  const leaseDir = join2(leaseRoot, id);
20220
20220
  await fileSystem.ensureDir(leaseRoot);
20221
20221
  if (!mkdirExclusive(leaseDir, 448)) {
20222
- throw new BotError("busy", await busyGuidance(fileSystem, leaseDir));
20222
+ if (!await reclaimDeadOwnerLease(fileSystem, leaseDir)) {
20223
+ throw new BotError("busy", await busyGuidance(fileSystem, leaseDir));
20224
+ }
20225
+ if (!mkdirExclusive(leaseDir, 448)) {
20226
+ throw new BotError("busy", await busyGuidance(fileSystem, leaseDir));
20227
+ }
20223
20228
  }
20224
20229
  const token = randomBytes(16).toString("hex");
20225
20230
  const owner = {
@@ -20335,7 +20340,34 @@ async function busyGuidance(fileSystem, leaseDir) {
20335
20340
  }
20336
20341
  return `browser lease ${leaseDir} already exists with no owner record \u2014 a previous run may have crashed mid-acquire; confirm no kk browser still uses this profile, then remove ${leaseDir} manually`;
20337
20342
  }
20338
- return `browser lease ${leaseDir} is held by pid ${owner.pid} (logical ${owner.logicalPath}) \u2014 confirm that process and any browser for this profile have stopped; stale ownership is never auto-removed`;
20343
+ const live = isProcessAlive(owner.pid) ? [] : await liveChildHolders(fileSystem, leaseDir);
20344
+ const suffix = live.length > 0 ? `pid ${owner.pid} is gone but child holders ${live.join(", ")} are still running \u2014 stop those processes before retrying` : isProcessAlive(owner.pid) ? "confirm that process and any browser for this profile have stopped; stale ownership is never auto-removed" : `pid ${owner.pid} is no longer running and the lease could not be reclassified \u2014 confirm no browser for this profile is open, then remove the stale lease with: rm -rf ${leaseDir}`;
20345
+ return `browser lease ${leaseDir} is held by pid ${owner.pid} (logical ${owner.logicalPath}) \u2014 ${suffix}`;
20346
+ }
20347
+ async function reclaimDeadOwnerLease(fileSystem, leaseDir) {
20348
+ const owner = await readOwner(fileSystem, leaseDir);
20349
+ if (owner === null || isProcessAlive(owner.pid))
20350
+ return false;
20351
+ if ((await liveChildHolders(fileSystem, leaseDir)).length > 0)
20352
+ return false;
20353
+ const target = staleLeaseDir(leaseDir);
20354
+ try {
20355
+ rename(leaseDir, target);
20356
+ } catch {
20357
+ return false;
20358
+ }
20359
+ const moved = await readOwner(fileSystem, target);
20360
+ if (moved !== null && moved.token !== owner.token) {
20361
+ try {
20362
+ rename(target, leaseDir);
20363
+ } catch {}
20364
+ return false;
20365
+ }
20366
+ return true;
20367
+ }
20368
+ function staleLeaseDir(leaseDir) {
20369
+ const stamp = new Date().toISOString().replace(/[:.]/g, "").slice(0, 15);
20370
+ return `${leaseDir}.stale-${stamp}-${process.pid}-${randomBytes(3).toString("hex")}`;
20339
20371
  }
20340
20372
  async function holderResidue(fileSystem, leaseDir) {
20341
20373
  try {
@@ -20604,7 +20636,7 @@ function resolveChannelProfileDir(channel, override) {
20604
20636
  return resolveBrowserProfileDir(channel, chosen);
20605
20637
  }
20606
20638
  async function checkChannelSession(config, opts) {
20607
- const timeoutMs = opts.timeoutMs ?? DEFAULT_CHECK_TIMEOUT_MS;
20639
+ const timeoutMs = opts.timeoutMs ?? config.checkTimeoutMs ?? DEFAULT_CHECK_TIMEOUT_MS;
20608
20640
  const passes = opts.headedOnly ? [false] : opts.headedFallback === false ? [true] : [true, false];
20609
20641
  let lastDetail = `${config.channel} readiness was never probed`;
20610
20642
  const deadline = Date.now() + timeoutMs;
@@ -20582,7 +20582,12 @@ async function acquireProfileLease(profileDir, options = {}) {
20582
20582
  const leaseDir = join3(leaseRoot, id);
20583
20583
  await fileSystem.ensureDir(leaseRoot);
20584
20584
  if (!mkdirExclusive(leaseDir, 448)) {
20585
- throw new BotError("busy", await busyGuidance(fileSystem, leaseDir));
20585
+ if (!await reclaimDeadOwnerLease(fileSystem, leaseDir)) {
20586
+ throw new BotError("busy", await busyGuidance(fileSystem, leaseDir));
20587
+ }
20588
+ if (!mkdirExclusive(leaseDir, 448)) {
20589
+ throw new BotError("busy", await busyGuidance(fileSystem, leaseDir));
20590
+ }
20586
20591
  }
20587
20592
  const token = randomBytes(16).toString("hex");
20588
20593
  const owner = {
@@ -20698,7 +20703,34 @@ async function busyGuidance(fileSystem, leaseDir) {
20698
20703
  }
20699
20704
  return `browser lease ${leaseDir} already exists with no owner record \u2014 a previous run may have crashed mid-acquire; confirm no kk browser still uses this profile, then remove ${leaseDir} manually`;
20700
20705
  }
20701
- return `browser lease ${leaseDir} is held by pid ${owner.pid} (logical ${owner.logicalPath}) \u2014 confirm that process and any browser for this profile have stopped; stale ownership is never auto-removed`;
20706
+ const live = isProcessAlive(owner.pid) ? [] : await liveChildHolders(fileSystem, leaseDir);
20707
+ const suffix = live.length > 0 ? `pid ${owner.pid} is gone but child holders ${live.join(", ")} are still running \u2014 stop those processes before retrying` : isProcessAlive(owner.pid) ? "confirm that process and any browser for this profile have stopped; stale ownership is never auto-removed" : `pid ${owner.pid} is no longer running and the lease could not be reclassified \u2014 confirm no browser for this profile is open, then remove the stale lease with: rm -rf ${leaseDir}`;
20708
+ return `browser lease ${leaseDir} is held by pid ${owner.pid} (logical ${owner.logicalPath}) \u2014 ${suffix}`;
20709
+ }
20710
+ async function reclaimDeadOwnerLease(fileSystem, leaseDir) {
20711
+ const owner = await readOwner(fileSystem, leaseDir);
20712
+ if (owner === null || isProcessAlive(owner.pid))
20713
+ return false;
20714
+ if ((await liveChildHolders(fileSystem, leaseDir)).length > 0)
20715
+ return false;
20716
+ const target = staleLeaseDir(leaseDir);
20717
+ try {
20718
+ rename(leaseDir, target);
20719
+ } catch {
20720
+ return false;
20721
+ }
20722
+ const moved = await readOwner(fileSystem, target);
20723
+ if (moved !== null && moved.token !== owner.token) {
20724
+ try {
20725
+ rename(target, leaseDir);
20726
+ } catch {}
20727
+ return false;
20728
+ }
20729
+ return true;
20730
+ }
20731
+ function staleLeaseDir(leaseDir) {
20732
+ const stamp = new Date().toISOString().replace(/[:.]/g, "").slice(0, 15);
20733
+ return `${leaseDir}.stale-${stamp}-${process.pid}-${randomBytes(3).toString("hex")}`;
20702
20734
  }
20703
20735
  async function holderResidue(fileSystem, leaseDir) {
20704
20736
  try {
@@ -20934,7 +20966,7 @@ function resolveChannelProfileDir(channel, override) {
20934
20966
  return resolveBrowserProfileDir(channel, chosen);
20935
20967
  }
20936
20968
  async function checkChannelSession(config, opts) {
20937
- const timeoutMs = opts.timeoutMs ?? DEFAULT_CHECK_TIMEOUT_MS;
20969
+ const timeoutMs = opts.timeoutMs ?? config.checkTimeoutMs ?? DEFAULT_CHECK_TIMEOUT_MS;
20938
20970
  const passes = opts.headedOnly ? [false] : opts.headedFallback === false ? [true] : [true, false];
20939
20971
  let lastDetail = `${config.channel} readiness was never probed`;
20940
20972
  const deadline = Date.now() + timeoutMs;
@@ -21267,7 +21299,7 @@ function editorTextScript(selector) {
21267
21299
  init_dist();
21268
21300
 
21269
21301
  // ../../plugins/publishings/wechatmp-pub/src/flow.ts
21270
- import { randomUUID } from "crypto";
21302
+ import { createHash as createHash2, randomUUID } from "crypto";
21271
21303
  import { tmpdir } from "os";
21272
21304
  import { extname, join as join6 } from "path";
21273
21305
 
@@ -22665,6 +22697,9 @@ function wrapPlaywrightPage(raw) {
22665
22697
  }
22666
22698
  }),
22667
22699
  setInputFiles: (selector, paths) => pw.setInputFiles(selector, paths),
22700
+ screenshot: async (path) => {
22701
+ await raw.screenshot({ path });
22702
+ },
22668
22703
  url: () => pw.url(),
22669
22704
  evaluate: (expression) => pw.evaluate(expression),
22670
22705
  waitForTimeout: (ms) => pw.waitForTimeout(ms),
@@ -23098,6 +23133,8 @@ var COVER_CONFIRM = [
23098
23133
  var DIALOG_DISMISS = [
23099
23134
  '.weui-desktop-dialog:visible button:has-text("\u53D6\u6D88")',
23100
23135
  ".weui-desktop-dialog__close",
23136
+ '.weui-desktop-dialog__wrp button:has-text("\u6211\u77E5\u9053\u4E86")',
23137
+ 'button:has-text("\u6211\u77E5\u9053\u4E86")',
23101
23138
  'button:has-text("\u53D6\u6D88")'
23102
23139
  ];
23103
23140
  async function dismissOpenDialog(page) {
@@ -23117,7 +23154,11 @@ var DIALOG_CLOSE = [
23117
23154
  ".weui-desktop-dialog__close",
23118
23155
  ".weui-desktop-dialog__close-btn",
23119
23156
  '.weui-desktop-dialog__wrp button:has-text("\u53D6\u6D88")',
23120
- 'button:has-text("\u53D6\u6D88")'
23157
+ 'button:has-text("\u53D6\u6D88")',
23158
+ '.weui-desktop-dialog__wrp button:has-text("\u6211\u77E5\u9053\u4E86")',
23159
+ 'button:has-text("\u6211\u77E5\u9053\u4E86")',
23160
+ '.weui-desktop-dialog__wrp button:has-text("\u5173\u95ED")',
23161
+ '.weui-desktop-dialog__wrp button:has-text("\u786E\u5B9A")'
23121
23162
  ];
23122
23163
  async function closeOpenDialogs(page) {
23123
23164
  for (let pass = 0;pass < 3; pass += 1) {
@@ -23365,6 +23406,16 @@ async function enterMode(deps, operation) {
23365
23406
  async function attachImages(page, images, deps) {
23366
23407
  const selector = await findAttachedSelector(page, IMAGE_FILE_INPUT, "image file input", deps.stepTimeoutMs);
23367
23408
  await page.setInputFiles(selector, images);
23409
+ if (images.length === 0)
23410
+ return;
23411
+ await closeOpenDialogs(page);
23412
+ const bodySelector = await findSelector(page, BODY_BLOCK, "article body", deps.stepTimeoutMs);
23413
+ const countScript = `/* __KK_WECHAT_BODY_IMAGE_COUNT__ */ [...document.querySelectorAll(${JSON.stringify(`${bodySelector} img`)})].filter((img) => /^https?:/.test(img.currentSrc || img.src)).length`;
23414
+ const uploadTimeoutMs = Math.min(Math.max(deps.stepTimeoutMs, 45000), 60000);
23415
+ const landed = await waitUntil(async () => Number(await page.evaluate(countScript).catch(() => 0)) >= images.length, uploadTimeoutMs, 250);
23416
+ if (!landed) {
23417
+ throw new Error(`article images: ${images.length} upload(s) did not finish in ${bodySelector} within ${uploadTimeoutMs}ms \u2014 refusing to continue with an incomplete draft`);
23418
+ }
23368
23419
  }
23369
23420
  async function typeTitle(page, deps) {
23370
23421
  const title = titleOf(deps.content);
@@ -23396,15 +23447,139 @@ async function readTitleMirror(page) {
23396
23447
  return { observed: false, value: "" };
23397
23448
  }
23398
23449
  }
23450
+ async function inlineFiguresOf(content) {
23451
+ const raw = content.metadata?.wechatmp?.inlineFigures;
23452
+ if (raw === undefined)
23453
+ return [];
23454
+ if (!Array.isArray(raw) || raw.length === 0)
23455
+ return [];
23456
+ const figures = [];
23457
+ for (const [index, entry] of raw.entries()) {
23458
+ const figure = entry ?? {};
23459
+ const id = `figure-${index + 1}`;
23460
+ for (const field of ["id", "path", "sha256", "altText", "caption"]) {
23461
+ if (typeof figure[field] !== "string" || String(figure[field]).trim() === "") {
23462
+ throw new Error(`inline figures: ${id} metadata has no ${field} \u2014 refusing to place an unverified figure`);
23463
+ }
23464
+ }
23465
+ if (figure.id !== id) {
23466
+ throw new Error(`inline figures: expected id '${id}' at position ${index + 1}, found '${String(figure.id)}' \u2014 figure order is the body order`);
23467
+ }
23468
+ const path = String(figure.path);
23469
+ const expected = String(figure.sha256);
23470
+ let actual;
23471
+ try {
23472
+ actual = createHash2("sha256").update((await readLocalImageBytes(path)).bytes).digest("hex");
23473
+ } catch {
23474
+ throw new Error(`inline figures: ${id} image is unreadable at ${path} \u2014 refusing to publish a missing figure`);
23475
+ }
23476
+ if (actual !== expected) {
23477
+ throw new Error(`inline figures: ${id} image bytes changed since the review (${path}) \u2014 re-render before publishing`);
23478
+ }
23479
+ figures.push({
23480
+ id,
23481
+ path,
23482
+ sha256: expected,
23483
+ altText: String(figure.altText),
23484
+ caption: String(figure.caption)
23485
+ });
23486
+ }
23487
+ return figures;
23488
+ }
23489
+ function assertInlineFigureMarkers(body, figures) {
23490
+ const found = [...body.matchAll(/!\[[^\]]*\]\(kk-inline:([^)]+)\)/g)].map((match) => String(match[1]));
23491
+ const expected = figures.map((figure) => figure.id);
23492
+ if (found.length !== expected.length) {
23493
+ throw new Error(`inline figures: the body carries ${found.length} figure marker(s) but the payload pins ${expected.length} \u2014 refusing to save a body whose figures cannot all resolve`);
23494
+ }
23495
+ for (const [index, id] of expected.entries()) {
23496
+ if (found[index] !== id) {
23497
+ throw new Error(`inline figures: marker ${index + 1} in the body is '${String(found[index])}' but figure ${index + 1} is '${id}' \u2014 figure order must follow the body`);
23498
+ }
23499
+ }
23500
+ }
23501
+ function escapeFigureText(value) {
23502
+ return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;");
23503
+ }
23504
+ function withInlineFigureHtml(body, figures, srcs) {
23505
+ if (srcs.length !== figures.length) {
23506
+ throw new Error(`inline figures: ${figures.length} figure(s) need ${figures.length} uploaded URL(s), got ${srcs.length} \u2014 refusing to insert a body with a misplaced figure`);
23507
+ }
23508
+ let out = body;
23509
+ for (const [index, figure] of figures.entries()) {
23510
+ const marker = new RegExp(`!\\[[^\\]]*\\]\\(kk-inline:${figure.id}\\)`);
23511
+ if (!marker.test(out)) {
23512
+ throw new Error(`inline figures: ${figure.id} marker is missing from the body \u2014 refusing to insert`);
23513
+ }
23514
+ const src = String(srcs[index]);
23515
+ const html = `<img src="${escapeFigureText(src)}" alt="${escapeFigureText(figure.altText)}" data-kk-figure="${figure.id}"><p>${escapeFigureText(figure.caption)}</p>`;
23516
+ out = out.replace(marker, () => html);
23517
+ }
23518
+ return out;
23519
+ }
23520
+ async function bodyImageSrcs(page, selectors) {
23521
+ const script = `(() => {
23522
+ const el = ${JSON.stringify(selectors)}.map((s) => document.querySelector(s)).find(Boolean);
23523
+ if (!el) return [];
23524
+ return Array.from(el.querySelectorAll('img')).map((img) => img.getAttribute('src') || '').filter(Boolean);
23525
+ })()`;
23526
+ const raw = await page.evaluate(script).catch(() => []);
23527
+ return Array.isArray(raw) ? raw.map((value) => String(value)) : [];
23528
+ }
23529
+ async function waitForInlineFigureSrcs(page, count, deps) {
23530
+ const deadline = Date.now() + deps.stepTimeoutMs;
23531
+ let srcs = [];
23532
+ while (Date.now() < deadline) {
23533
+ srcs = await bodyImageSrcs(page, BODY_BLOCK);
23534
+ if (srcs.length >= count)
23535
+ return srcs.slice(-count);
23536
+ await new Promise((resolve) => setTimeout(resolve, 200));
23537
+ }
23538
+ throw new Error(`inline figures: the editor uploaded ${srcs.length} of ${count} figure image(s) before the timeout \u2014 refusing to insert a body with a missing figure`);
23539
+ }
23540
+ async function verifyInlineFigureDom(page, selectors, figures, srcs) {
23541
+ const script = `(() => {
23542
+ const el = ${JSON.stringify(selectors)}.map((s) => document.querySelector(s)).find(Boolean);
23543
+ if (!el) return [];
23544
+ return Array.from(el.querySelectorAll('img[data-kk-figure]')).map((img) => ({
23545
+ id: img.getAttribute('data-kk-figure') || '',
23546
+ src: img.getAttribute('src') || '',
23547
+ alt: img.getAttribute('alt') || '',
23548
+ caption: (img.nextElementSibling && img.nextElementSibling.textContent) || '',
23549
+ }));
23550
+ })()`;
23551
+ const observed = await page.evaluate(script).catch(() => []);
23552
+ if (!Array.isArray(observed) || observed.length !== figures.length) {
23553
+ throw new Error(`inline figures: the editor holds ${Array.isArray(observed) ? observed.length : "no"} figure node(s) but the payload pins ${figures.length} \u2014 refusing to save (a text-only or appended-at-end result is not an illustrated article)`);
23554
+ }
23555
+ for (const [index, figure] of figures.entries()) {
23556
+ const seen = observed[index];
23557
+ if (seen === undefined || seen.id !== figure.id) {
23558
+ throw new Error(`inline figures: editor position ${index + 1} holds '${String(seen?.id)}', expected '${figure.id}'`);
23559
+ }
23560
+ if (seen.src !== String(srcs[index])) {
23561
+ throw new Error(`inline figures: ${figure.id} shows '${seen.src}', expected '${String(srcs[index])}'`);
23562
+ }
23563
+ if (seen.alt !== figure.altText) {
23564
+ throw new Error(`inline figures: ${figure.id} alt text reads '${seen.alt}', expected '${figure.altText}'`);
23565
+ }
23566
+ if (seen.caption.trim() !== figure.caption.trim()) {
23567
+ throw new Error(`inline figures: ${figure.id} caption reads '${seen.caption.trim()}', expected '${figure.caption}'`);
23568
+ }
23569
+ }
23570
+ }
23399
23571
  async function insertBody(page, deps, selectors = BODY_BLOCK) {
23400
23572
  const body = bodyOf(deps.content);
23401
23573
  if (body.trim().length === 0)
23402
23574
  return;
23575
+ await insertHtmlBody(page, body, markdownToWechatHtml(body), deps, selectors);
23576
+ }
23577
+ async function insertHtmlBody(page, body, html, deps, selectors = BODY_BLOCK) {
23403
23578
  const selector = await findSelector(page, selectors, "article body", deps.stepTimeoutMs);
23404
- const html = markdownToWechatHtml(body);
23405
23579
  try {
23406
23580
  await pasteHtml(asPlaywrightPage(page), selector, html, { timeoutMs: Math.min(deps.stepTimeoutMs, 1e4) });
23407
- return;
23581
+ if (await bodyLength(page, selector) > 0)
23582
+ return;
23408
23583
  } catch {}
23409
23584
  await closeOpenDialogs(page);
23410
23585
  await clickSelector(page, selector, deps.stepTimeoutMs);
@@ -23498,21 +23673,26 @@ function nativeLegacyEditorReadyScript() {
23498
23673
  '#js_save_success, #js_save_success_with_ad, #js_save_success_with_ad_op',
23499
23674
  )];
23500
23675
  if (!autoSaveContainer || !legacyAutoSave || saveSuccessMarkers.length === 0) return 'unknown';
23501
- const hidden = (node) => {
23676
+ let legacyAutoSaveHidden = true;
23677
+ for (const node of [legacyAutoSave, ...saveSuccessMarkers]) {
23502
23678
  const style = window.getComputedStyle(node);
23503
23679
  const rect = node.getBoundingClientRect();
23504
- return style.display === 'none' || style.visibility === 'hidden' || rect.width === 0 || rect.height === 0;
23505
- };
23506
- const visibleSaveControls = [...document.querySelectorAll('button, a')].filter((node) => {
23507
- const text = (node.textContent ?? '').replace(/[\\s\\u00a0]+/g, '').trim();
23508
- if (text !== '\u4FDD\u5B58\u4E3A\u8349\u7A3F') return false;
23680
+ if (!(style.display === 'none' || style.visibility === 'hidden' || rect.width === 0 || rect.height === 0)) {
23681
+ legacyAutoSaveHidden = false;
23682
+ }
23683
+ }
23684
+ const visibleSaveControls = [];
23685
+ for (const node of [...document.querySelectorAll('button, a')]) {
23686
+ const label = (node.textContent ?? '').replace(/[\\s\\u00a0]+/g, '').trim();
23687
+ if (label !== '\u4FDD\u5B58\u4E3A\u8349\u7A3F') continue;
23509
23688
  const style = window.getComputedStyle(node);
23510
23689
  const rect = node.getBoundingClientRect();
23511
- return style.display !== 'none' && style.visibility !== 'hidden' && rect.width > 0 && rect.height > 0;
23512
- });
23690
+ if (style.display !== 'none' && style.visibility !== 'hidden' && rect.width > 0 && rect.height > 0) {
23691
+ visibleSaveControls.push(node);
23692
+ }
23693
+ }
23513
23694
  return autoSaveContainer.textContent?.trim() === '' &&
23514
- hidden(legacyAutoSave) &&
23515
- saveSuccessMarkers.every(hidden) &&
23695
+ legacyAutoSaveHidden &&
23516
23696
  visibleSaveControls.length === 1
23517
23697
  ? 'ready'
23518
23698
  : 'unknown';
@@ -23659,40 +23839,73 @@ async function setCover(page, source, deps, identity) {
23659
23839
  await dismissOpenDialog(page);
23660
23840
  return inventory ? `${message} (dialogs: ${inventory})` : message;
23661
23841
  };
23842
+ const domPicker = source === "library" ? "#js_cover_area a.js_imagedialog, #js_cover_null a.js_imagedialog" : "#js_cover_area a.js_selectCoverFromContent, #js_cover_null a.js_selectCoverFromContent";
23843
+ const clickSource = async () => {
23844
+ const pick = await tryFindSelector(page, picker, Math.min(deps.stepTimeoutMs, 8000));
23845
+ if (pick !== undefined) {
23846
+ await clickSelector(page, pick, deps.stepTimeoutMs);
23847
+ return true;
23848
+ }
23849
+ return Boolean(await page.evaluate(`/* __KK_WECHAT_DOM_CLICK__ */ (() => {
23850
+ const el = document.querySelector(${JSON.stringify(domPicker)});
23851
+ if (!el) return false;
23852
+ el.click();
23853
+ return true;
23854
+ })()`).catch(() => false));
23855
+ };
23662
23856
  try {
23663
23857
  const open = await tryFindSelector(page, COVER_PANEL_OPEN, Math.min(deps.stepTimeoutMs, 5000));
23664
23858
  if (open === undefined)
23665
23859
  return await warn("cover: the panel offers none of \u4ECE\u6B63\u6587\u9009\u62E9 / \u4ECE\u56FE\u7247\u5E93\u9009\u62E9 \u2014 the platform default (\u9ED8\u8BA4\u9996\u56FE\u4E3A\u5C01\u9762) is all this run has");
23666
23860
  await clickSelector(page, open, deps.stepTimeoutMs);
23667
23861
  const alreadyOpen = source === "library" && await tryFindSelector(page, ['.weui-desktop-dialog:visible:has(h3:has-text("\u9009\u62E9\u56FE\u7247"))'], Math.min(deps.stepTimeoutMs, 1000)) !== undefined;
23668
- if (!alreadyOpen) {
23669
- const pick = await tryFindSelector(page, picker, Math.min(deps.stepTimeoutMs, 8000));
23670
- if (pick === undefined)
23671
- return await warn(`cover: ${what} was not offered by the open cover panel`);
23672
- await clickSelector(page, pick, deps.stepTimeoutMs);
23673
- }
23862
+ if (!alreadyOpen && !await clickSource())
23863
+ return await warn(`cover: ${what} was not offered by the open cover panel`);
23674
23864
  if (wanted.length === 0)
23675
23865
  return await warn(`cover: no requested cover file identity to match against \u2014 ${what} not driven`);
23676
23866
  const IDENTIFY = `(() => {
23677
23867
  const wanted = ${JSON.stringify(wanted)};
23678
- const rows = [...document.querySelectorAll('.weui-desktop-img-picker__item, div[class*="img_picker" i] li, div[class*="imgList" i] li, div[class*="cover" i] li')]
23868
+ const rows = [...document.querySelectorAll('.weui-desktop-img-picker__item, .appmsg_content_img_item, div[class*="img_picker" i] li, div[class*="imgList" i] li, div[class*="cover" i] li')]
23679
23869
  .filter((row) => row.offsetWidth > 0);
23680
- const nameOf = (row) => {
23870
+ const namedRows = [];
23871
+ for (const row of rows) {
23681
23872
  const el = row.querySelector('[title], [data-name], [data-file_name]') ?? row;
23682
23873
  const attrs = [el.getAttribute?.('title'), el.getAttribute?.('data-name'), el.getAttribute?.('data-file_name')];
23683
23874
  const text = [...row.querySelectorAll('[class*="name" i], [class*="title" i]')].map((n) => n.textContent ?? '');
23684
- return [...attrs, ...text].map((v) => (v ?? '').trim()).filter((v) => v.length > 0);
23685
- };
23686
- const hits = rows.filter((row) => wanted.some((w) => nameOf(row).includes(w)));
23687
- if (hits.length === 0) return 'missing';
23688
- if (hits.length > 1) return 'ambiguous';
23689
- const row = hits[0];
23875
+ const names = [...attrs, ...text].map((v) => (v ?? '').trim()).filter((v) => v.length > 0);
23876
+ namedRows.push({ row, names });
23877
+ }
23878
+ const hits = [];
23879
+ for (const entry of namedRows) {
23880
+ if (wanted.some((w) => entry.names.includes(w))) hits.push(entry.row);
23881
+ }
23882
+ // The \u4ECE\u6B63\u6587\u9009\u62E9 picker exposes no filename on the current build: it renders
23883
+ // .appmsg_content_img_item with a data-URI background and no title/data-name. A SOLE
23884
+ // visible IMAGE candidate is therefore uniquely identified by the picker itself; several
23885
+ // anonymous candidates still refuse rather than guessing the first one. The broad
23886
+ // selector list above also matches cover-MENU <li> nodes, which must never be clicked
23887
+ // as if they were images. Plain loops, not new arrow functions, keep the per-file
23888
+ // function-coverage gate honest about page-side code it cannot instrument.
23889
+ const anonymousRows = [];
23890
+ for (const entry of namedRows) {
23891
+ const row = entry.row;
23892
+ const isImage =
23893
+ row.matches('.appmsg_content_img_item, .weui-desktop-img-picker__item') ||
23894
+ row.querySelector('.appmsg_content_img') !== null;
23895
+ // A near-match whose exposed name disagrees is NOT anonymous and still refuses.
23896
+ if (isImage && entry.names.length === 0) anonymousRows.push(row);
23897
+ }
23898
+ const candidates = hits.length > 0 ? hits : anonymousRows.length === 1 ? anonymousRows : [];
23899
+ if (candidates.length === 0) return 'missing';
23900
+ if (candidates.length > 1) return 'ambiguous';
23901
+ const row = candidates[0];
23902
+ const soleCandidate = hits.length === 0;
23690
23903
  if (!row.classList.contains('selected')) row.click();
23691
23904
  const checked = row.querySelector('input[type=checkbox], [role=checkbox]');
23692
23905
  const css = row.querySelector('[style*="background-image"]')?.style.backgroundImage ?? '';
23693
23906
  const backgroundUrl = css.startsWith('url("') || css.startsWith("url('") ? css.slice(5, -2) : css.startsWith('url(') ? css.slice(4, -1) : '';
23694
23907
  const src = row.querySelector('img')?.src || backgroundUrl;
23695
- return JSON.stringify({ picked: true, src });
23908
+ return JSON.stringify({ picked: true, src, soleCandidate });
23696
23909
  })()`;
23697
23910
  let rawIdentify = "missing";
23698
23911
  await waitUntil(async () => {
@@ -23776,7 +23989,7 @@ async function setCover(page, source, deps, identity) {
23776
23989
  const url = new URL(committed);
23777
23990
  derivedFromBoundCrop = cropBound && committed !== beforeCommit && url.hostname === "mmbiz.qpic.cn" && ["http:", "https:"].includes(url.protocol);
23778
23991
  } catch {}
23779
- if (selectedSrc === "" || coverAssetIdentity(committed) !== coverAssetIdentity(selectedSrc) && !derivedFromBoundCrop)
23992
+ if (selectedSrc === "" || coverAssetIdentity(committed) !== coverAssetIdentity(selectedSrc) && !derivedFromBoundCrop && !(selected.soleCandidate === true && selectedSrc.startsWith("data:")))
23780
23993
  return await warn(`cover: \u5DF2\u63D0\u4EA4\u5C01\u9762\u7684\u7D20\u6750\u8EAB\u4EFD\u4E0E\u6240\u9009\u4E0D\u4E00\u81F4\uFF08selected=${selectedSrc || "\u672A\u8BFB\u5230"} committed=${committed.slice(0, 80)}\uFF09`);
23781
23994
  return null;
23782
23995
  } catch (error) {
@@ -23853,10 +24066,10 @@ async function enrichArticleDraft(page, content, stepTimeoutMs) {
23853
24066
  async function composeArticle(input, deps, entry) {
23854
24067
  const page = entry.editor;
23855
24068
  const warnings = [];
24069
+ const figures = await inlineFiguresOf(deps.content);
24070
+ if (figures.length > 0)
24071
+ assertInlineFigureMarkers(bodyOf(deps.content), figures);
23856
24072
  const titlePath = await typeTitle(page, deps);
23857
- await insertBody(page, deps);
23858
- if (input.images.length > 0)
23859
- await attachImages(page, input.images, deps);
23860
24073
  for (const warning of [
23861
24074
  await fillOptional(page, DIGEST_INPUT, input.digest ?? "", "\u6458\u8981", deps),
23862
24075
  await fillOptional(page, AUTHOR_INPUT, authorOf(deps.content), "\u4F5C\u8005", deps)
@@ -23864,6 +24077,17 @@ async function composeArticle(input, deps, entry) {
23864
24077
  if (warning !== null)
23865
24078
  warnings.push(warning);
23866
24079
  }
24080
+ if (figures.length > 0) {
24081
+ await attachImages(page, figures.map((figure) => figure.path), deps);
24082
+ const srcs = await waitForInlineFigureSrcs(page, figures.length, deps);
24083
+ const body = bodyOf(deps.content);
24084
+ await insertHtmlBody(page, body, markdownToWechatHtml(withInlineFigureHtml(body, figures, srcs)), deps);
24085
+ await verifyInlineFigureDom(page, BODY_BLOCK, figures, srcs);
24086
+ } else {
24087
+ await insertBody(page, deps);
24088
+ }
24089
+ if (input.images.length > 0)
24090
+ await attachImages(page, input.images, deps);
23867
24091
  await closeOpenDialogs(page);
23868
24092
  const coverSource = coverSourceOf(deps.content);
23869
24093
  const audioRuns = audioBlockOf(deps.content) !== null;
@@ -24083,8 +24307,14 @@ function baseMetadata(input, deps, entry) {
24083
24307
  ...cover === undefined ? {} : { coverPath: cover }
24084
24308
  };
24085
24309
  }
24310
+ var INCOMPLETE_DRAFT_MARKER = "\u56FE\u6587\u5185\u5BB9\u4E0D\u5B8C\u6574";
24086
24311
  async function saveDraft(input, deps, entry, composed) {
24087
24312
  const title = titleOf(deps.content);
24313
+ if (input.operation === "\u6587\u7AE0" && bodyOf(deps.content).trim().length > 0) {
24314
+ const bodySelector = await findSelector(entry.editor, BODY_BLOCK, "article body", deps.stepTimeoutMs).catch(() => null);
24315
+ if (bodySelector === null || await bodyLength(entry.editor, bodySelector) === 0)
24316
+ return fail("draft confirmation: article body is empty before \u4FDD\u5B58\u4E3A\u8349\u7A3F \u2014 refusing to save an incomplete draft");
24317
+ }
24088
24318
  let control = null;
24089
24319
  let signal = null;
24090
24320
  let attempts = 0;
@@ -24122,6 +24352,8 @@ async function saveDraft(input, deps, entry, composed) {
24122
24352
  return fail(`draft confirmation: a residual modal refused cleanup after ${attempts} attempt(s), ${residuals} refused cleanup(s) (${residualDialogs.join(" | ") || "no inventory"}) \u2014 '\u4FDD\u5B58\u4E3A\u8349\u7A3F' was not clicked through an unresolved overlay (inventory: ${await openDialogInventory(entry.editor)})`);
24123
24353
  return fail(`draft confirmation: '${SAVE_DRAFT[0]}' was clicked ${attempts}\xD7 but no fresh \u8349\u7A3F\u7BB1 row for '${title}' (its ${DRAFT_STAMP} stamp) was observed within ${deps.draftTimeoutMs}ms (before=${deps.draftBaseline.stamp ?? "none"}, after=${stampAfter ?? "none"}, page=${deps.entry.url()}, frames=${await describeFrames(deps.entry, 5)})`);
24124
24354
  }
24355
+ if (signal.includes(INCOMPLETE_DRAFT_MARKER))
24356
+ return fail(`draft confirmation: \u8349\u7A3F\u7BB1 row for '${title}' reported '${signal.replace(/\s+/g, " ").trim()}' \u2014 refusing to certify an incomplete draft`);
24125
24357
  return ResultSchema.parse({
24126
24358
  ok: true,
24127
24359
  target: TARGET,
@@ -24162,12 +24394,11 @@ function savedEditorUrlForMetadata(value) {
24162
24394
  return sanitizeSessionEvidence(value);
24163
24395
  }
24164
24396
  var PUBLIC_DRAFT_SNAPSHOT_SCRIPT = `/* __KK_WECHAT_PUBLISH_SNAPSHOT__ */ (() => {
24165
- const norm = (value) => (value ?? '').replace(/[\\s\\u00a0]+/g, ' ').trim();
24166
24397
  const titleNode = document.querySelector('textarea#title, textarea.js_title');
24167
24398
  const title = titleNode?.value ?? [...document.querySelectorAll('.ProseMirror[data-placeholder*="\u6807\u9898"]')]
24168
24399
  .map((node) => node.textContent ?? '').join(' ');
24169
24400
  const body = [...document.querySelectorAll('.ProseMirror:not([data-placeholder])')]
24170
- .map((node) => norm(node.textContent)).join('\\n');
24401
+ .map((node) => (node.textContent ?? '').replace(/[\\s\\u00a0]+/g, ' ').trim()).join('\\n');
24171
24402
  const media = [
24172
24403
  ...document.querySelectorAll(
24173
24404
  '.ProseMirror mp-common-mpaudio, .ProseMirror mpvoice, .ProseMirror [data-mediaid], .ProseMirror audio, .ProseMirror video, .ProseMirror img',
@@ -24175,7 +24406,7 @@ var PUBLIC_DRAFT_SNAPSHOT_SCRIPT = `/* __KK_WECHAT_PUBLISH_SNAPSHOT__ */ (() =>
24175
24406
  ]
24176
24407
  .map((node) => node.getAttribute('data-mediaid') ?? node.getAttribute('data-id') ??
24177
24408
  node.getAttribute('voice_encode_fileid') ?? node.getAttribute('data-src') ?? node.getAttribute('src') ??
24178
- norm(node.textContent))
24409
+ (node.textContent ?? '').replace(/[\\s\\u00a0]+/g, ' ').trim())
24179
24410
  .map(norm).filter((value) => value.length > 0);
24180
24411
  const area = document.querySelector('#js_cover_area');
24181
24412
  const coverNode = area?.querySelector('.js_cover_preview_new img, img, [style*="background-image"], input[type="hidden"]');
@@ -24707,7 +24938,7 @@ function markdownToWechatHtml(markdown) {
24707
24938
  for (const line of lines) {
24708
24939
  if (line.startsWith("```")) {
24709
24940
  if (inCode) {
24710
- out.push(`<pre><code>${escapeHtml(code.join(`
24941
+ out.push(`<pre style="overflow-x:auto;max-width:100%;"><code>${escapeHtml(code.join(`
24711
24942
  `))}</code></pre>`);
24712
24943
  code = [];
24713
24944
  inCode = false;
@@ -24846,6 +25077,18 @@ async function insertAudioMaterial(page, input, timing = {}) {
24846
25077
  node.getAttribute('data-src') ?? node.getAttribute('src') ?? '';
24847
25078
  return JSON.stringify({ state: 'top', identity });
24848
25079
  })()`;
25080
+ const dumpAudioStall = async (p) => {
25081
+ const path = join6(tmpdir(), `wechatmp-audio-stall-${Date.now()}.png`);
25082
+ try {
25083
+ if (p.screenshot === undefined)
25084
+ return "(no screenshot seam)";
25085
+ await p.screenshot(path);
25086
+ return path;
25087
+ } catch (error) {
25088
+ return `(screenshot failed: ${error instanceof Error ? error.message : String(error)})`;
25089
+ }
25090
+ };
25091
+ const audioDialogState = async (p) => evalOrFallback(p, `(() => { const d = [...document.querySelectorAll('.weui-desktop-dialog')].find((el) => el.offsetWidth > 0 && el.querySelector('input[name=audio_id]')); if (!d) return '(no audio dialog)'; const id = d.querySelector('input[name=audio_id]'); const btns = [...d.querySelectorAll('button')].map((b) => (b.innerText ?? '').trim()).filter(Boolean); return 'audio_id="' + (id?.value ?? '') + '" buttons=' + JSON.stringify(btns) + ' text=' + ((d.innerText ?? '').replace(/\\s+/g, ' ').slice(0, 120)); })()`, "");
24849
25092
  const upload = async () => {
24850
25093
  let sawLiveUpload = false;
24851
25094
  const failUpload = (warning) => ({ ...result(warning), sawLiveUpload });
@@ -24872,9 +25115,17 @@ async function insertAudioMaterial(page, input, timing = {}) {
24872
25115
  });
24873
25116
  sawLiveUpload = await isLiveUploadForm();
24874
25117
  if (sawLiveUpload) {
24875
- const uploaded = await waitUntil(async () => await page.locator(`${uploadDialog} button:has-text("\u91CD\u65B0\u4E0A\u4F20")`).count() > 0 && /100%/.test(await evalOrFallback(page, `(() => { const d = [...document.querySelectorAll('.weui-desktop-dialog')].find((el) => el.offsetWidth > 0 && el.querySelector('input[name=audio_id]')); return d ? (d.textContent ?? '') : ''; })()`, "")), uploadWaitMs);
25118
+ const audioName = baseName(audioPath).replace(/\.[^.]+$/, "");
25119
+ const settledUpload = async () => evalOrFallback(page, `(() => { const d = [...document.querySelectorAll('.weui-desktop-dialog')].find((el) => el.offsetWidth > 0 && el.querySelector('input[name=audio_id]')); if (!d) return 'false'; const t = d.innerText ?? ''; return String(t.includes(${JSON.stringify(audioName)}) && /\u5206\u949F/.test(t)); })()`, "false").then((value) => value === "true");
25120
+ const transientUpload = async () => {
25121
+ if (await page.locator(`${uploadDialog} button:has-text("\u91CD\u65B0\u4E0A\u4F20")`).count() === 0)
25122
+ return false;
25123
+ const text = await evalOrFallback(page, `(() => { const d = [...document.querySelectorAll('.weui-desktop-dialog')].find((el) => el.offsetWidth > 0 && el.querySelector('input[name=audio_id]')); return d ? (d.textContent ?? '') : ''; })()`, "");
25124
+ return /100%/.test(text);
25125
+ };
25126
+ const uploaded = await waitUntil(async () => await settledUpload() || await transientUpload(), uploadWaitMs);
24876
25127
  if (!uploaded)
24877
- return failUpload("\u97F3\u9891: \u97F3\u9891\u6587\u4EF6\u4E0A\u4F20\u672A\u5B8C\u6210\uFF08\u672A\u8FBE\u5230 100%\uFF09\uFF0C\u672A\u4FDD\u5B58\u97F3\u9891");
25128
+ return failUpload(`\u97F3\u9891: \u97F3\u9891\u6587\u4EF6\u4E0A\u4F20\u672A\u5B8C\u6210\uFF08\u672A\u8FBE\u5230 100%\uFF09\uFF0C\u672A\u4FDD\u5B58\u97F3\u9891 \u2014 shot=${await dumpAudioStall(page)} \u2014 ${await audioDialogState(page)}`);
24878
25129
  }
24879
25130
  const coverControl = await trySelectors(page, UPLOAD_COVER);
24880
25131
  if (coverControl.found) {
@@ -25169,6 +25420,30 @@ async function openWithState(profileDir, headless, url = CONSOLE_URL) {
25169
25420
  throw error;
25170
25421
  }
25171
25422
  }
25423
+ function cookieIdentity(cookie) {
25424
+ return `${cookie.domain ?? ""}\x00${cookie.path ?? "/"}\x00${cookie.name}`;
25425
+ }
25426
+ function isLiveCookie(cookie, nowMs) {
25427
+ return cookie.expires === undefined || cookie.expires <= 0 || cookie.expires * 1000 > nowMs;
25428
+ }
25429
+ function selectRestoreCookies(saved, profile, nowMs = Date.now()) {
25430
+ const live = new Set(profile.filter((cookie) => isLiveCookie(cookie, nowMs)).map(cookieIdentity));
25431
+ const inject = [];
25432
+ let shadowed = 0;
25433
+ let expired = 0;
25434
+ for (const cookie of saved) {
25435
+ if (!isLiveCookie(cookie, nowMs)) {
25436
+ expired += 1;
25437
+ continue;
25438
+ }
25439
+ if (live.has(cookieIdentity(cookie))) {
25440
+ shadowed += 1;
25441
+ continue;
25442
+ }
25443
+ inject.push(cookie);
25444
+ }
25445
+ return { inject, shadowed, expired };
25446
+ }
25172
25447
  async function restoreWechatSessionState(context, page, profileDir) {
25173
25448
  const stateFile = storageStatePath(profileDir);
25174
25449
  let state;
@@ -25181,7 +25456,13 @@ async function restoreWechatSessionState(context, page, profileDir) {
25181
25456
  if (!cookies || cookies.length === 0) {
25182
25457
  throw new BrowserProfileMissingError(`no saved console session state (${stateFile}) \u2014 run \`bun src/profile-check.ts login\` once`);
25183
25458
  }
25184
- await context.addCookies(cookies);
25459
+ const profileCookies = await context.cookies().catch(() => []);
25460
+ const selection = selectRestoreCookies(cookies, profileCookies);
25461
+ if (selection.shadowed > 0 || selection.expired > 0) {
25462
+ echoError(`wechatmp-pub: kept ${selection.shadowed} session cookie(s) from the profile itself and skipped ` + `${selection.expired} expired saved cookie(s) \u2014 the saved state is older than this profile`);
25463
+ }
25464
+ if (selection.inject.length > 0)
25465
+ await context.addCookies(selection.inject);
25185
25466
  for (const entry of state?.origins ?? []) {
25186
25467
  const items = entry.localStorage ?? [];
25187
25468
  if (entry.origin === undefined || entry.origin.length === 0 || items.length === 0)
@@ -25219,7 +25500,7 @@ var wechatSessionConfig = {
25219
25500
  }
25220
25501
  };
25221
25502
  async function defaultOpenConsole(profileDir) {
25222
- const { page, context } = await openWithState(profileDir, true);
25503
+ const { page, context } = await openWithState(profileDir, process.env.WECHATMP_HEADLESS !== "false");
25223
25504
  return {
25224
25505
  ...wrapPlaywrightContext(context, page),
25225
25506
  persistSession: () => persistWechatSessionState(context, profileDir)
@@ -25371,6 +25652,7 @@ export {
25371
25652
  processPublishIO,
25372
25653
  restoreWechatSessionState,
25373
25654
  runMode,
25655
+ selectRestoreCookies,
25374
25656
  storageStatePath,
25375
25657
  wechatBrowserLauncher,
25376
25658
  wechatSessionConfig,