@gobing-ai/knowledge-kit 0.1.23 → 0.1.25

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 (106) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/dist/index.js +418 -114
  3. package/package.json +5 -5
  4. package/plugins/generations/content-gen/dist/index.js +9 -9
  5. package/plugins/generations/core-facts-gen/dist/index.js +12 -12
  6. package/plugins/generations/daily-article-gen/dist/index.js +12 -12
  7. package/plugins/generations/dailynews-gen/dist/index.js +11 -11
  8. package/plugins/generations/dailynews-gen/src/script-plan.ts +2 -2
  9. package/plugins/generations/episode-plan-gen/dist/index.js +59 -18
  10. package/plugins/generations/episode-plan-gen/src/index.ts +71 -7
  11. package/plugins/generations/gemini-tts/dist/index.js +9 -9
  12. package/plugins/generations/image-gen/dist/index.js +9 -9
  13. package/plugins/generations/music-gen/dist/index.js +33 -29
  14. package/plugins/generations/music-gen/src/audio/measure.ts +25 -20
  15. package/plugins/generations/news-report-gen/dist/index.js +12 -12
  16. package/plugins/generations/vibe-voice-tts/dist/index.js +9 -9
  17. package/plugins/generations/voice-gen/dist/index.js +9 -9
  18. package/plugins/generations/voxcpm-tts/dist/index.js +9 -9
  19. package/plugins/ingestions/aihot-ingest/dist/index.js +12 -12
  20. package/plugins/ingestions/horizon-ingest/dist/index.js +12 -12
  21. package/plugins/ingestions/karakeep-local/dist/index.js +13 -13
  22. package/plugins/ingestions/last30days-ingest/dist/index.js +12 -12
  23. package/plugins/ingestions/web-search/dist/index.js +10 -10
  24. package/plugins/kk/decisions/extract/ai-news.yaml +8 -1
  25. package/plugins/kk/plugin.json +1 -1
  26. package/plugins/kk/publish-presets/daily-ai-voice.json +20 -20
  27. package/plugins/kk/publish-presets/itc-main.json +39 -23
  28. package/plugins/kk/scripts/cover-compositor.ts +104 -26
  29. package/plugins/kk/scripts/daily-stages.ts +704 -53
  30. package/plugins/kk/scripts/kk-workflow-stages.ts +149 -6
  31. package/plugins/kk/scripts/series-names.ts +16 -3
  32. package/plugins/kk/skills/content-safety/references/platforms/apple-podcasts.md +12 -5
  33. package/plugins/kk/skills/content-safety/references/platforms/wechatmp.md +8 -0
  34. package/plugins/kk/skills/content-safety/references/platforms/xiaoyuzhou.md +5 -0
  35. package/plugins/kk/skills/daily-news-cover/SKILL.md +96 -0
  36. package/plugins/kk/skills/daily-news-illustrations/SKILL.md +123 -0
  37. package/plugins/kk/skills/news-editorial/SKILL.md +5 -3
  38. package/plugins/kk/skills/news-editorial/references/daily-visual-composition.md +150 -0
  39. package/plugins/kk/skills/news-editorial/references/style-contract.zh.md +3 -3
  40. package/plugins/kk/workflows/kk-article-generate.yaml +13 -1
  41. package/plugins/kk/workflows/kk-daily-ai-voice.yaml +6 -3
  42. package/plugins/kk/workflows/kk-daily-ai-voice2.yaml +6 -4
  43. package/plugins/kk/workflows/kk-news-generate.yaml +74 -1
  44. package/plugins/publishings/bilibili-pub/dist/index.js +25 -24
  45. package/plugins/publishings/bilibili-pub/dist/profile-check.js +25 -24
  46. package/plugins/publishings/cnblogs-pub/dist/index.js +25 -24
  47. package/plugins/publishings/cnblogs-pub/dist/profile-check.js +25 -24
  48. package/plugins/publishings/csdn-pub/dist/index.js +25 -24
  49. package/plugins/publishings/csdn-pub/dist/profile-check.js +25 -24
  50. package/plugins/publishings/emdash-pub/dist/index.js +9 -9
  51. package/plugins/publishings/infoq-pub/dist/index.js +25 -24
  52. package/plugins/publishings/infoq-pub/dist/profile-check.js +25 -24
  53. package/plugins/publishings/jike-pub/dist/index.js +25 -24
  54. package/plugins/publishings/jike-pub/dist/profile-check.js +25 -24
  55. package/plugins/publishings/juejin-pub/dist/index.js +25 -24
  56. package/plugins/publishings/juejin-pub/dist/profile-check.js +25 -24
  57. package/plugins/publishings/linkedin-pub/dist/index.js +85 -26
  58. package/plugins/publishings/linkedin-pub/dist/profile-check.js +25 -24
  59. package/plugins/publishings/linkedin-pub/src/index.ts +93 -6
  60. package/plugins/publishings/medium-pub/dist/index.js +9206 -287
  61. package/plugins/publishings/medium-pub/dist/profile-check.js +21174 -0
  62. package/plugins/publishings/medium-pub/package.json +3 -1
  63. package/plugins/publishings/medium-pub/plugin.json +6 -1
  64. package/plugins/publishings/medium-pub/src/browser-rail.ts +280 -0
  65. package/plugins/publishings/medium-pub/src/index.ts +17 -1
  66. package/plugins/publishings/medium-pub/src/profile-check.ts +27 -0
  67. package/plugins/publishings/podcast-pub/dist/index.js +240 -37
  68. package/plugins/publishings/podcast-pub/src/index.ts +154 -3
  69. package/plugins/publishings/podcast-pub/src/seo.ts +25 -8
  70. package/plugins/publishings/podcast-pub/src/show-notes-brief.ts +93 -23
  71. package/plugins/publishings/podcast-pub/src/show-notes.ts +26 -6
  72. package/plugins/publishings/qiita-pub/dist/index.js +9 -9
  73. package/plugins/publishings/shipinhao-pub/dist/index.js +29 -26
  74. package/plugins/publishings/shipinhao-pub/dist/profile-check.js +28 -26
  75. package/plugins/publishings/shipinhao-pub/src/flow.ts +5 -0
  76. package/plugins/publishings/shipinhao-pub/src/selectors.ts +13 -5
  77. package/plugins/publishings/sspai-pub/dist/index.js +25 -24
  78. package/plugins/publishings/sspai-pub/dist/profile-check.js +25 -24
  79. package/plugins/publishings/substack-pub/dist/index.js +25 -24
  80. package/plugins/publishings/substack-pub/dist/profile-check.js +25 -24
  81. package/plugins/publishings/surfdash-pub/dist/index.js +200 -92
  82. package/plugins/publishings/surfdash-pub/src/digest-check.ts +30 -1
  83. package/plugins/publishings/surfdash-pub/src/index.ts +94 -75
  84. package/plugins/publishings/surfdash-pub/src/media-upload.ts +83 -0
  85. package/plugins/publishings/surfdash-pub/src/patch.ts +28 -23
  86. package/plugins/publishings/surfdash-pub/src/topic-claims.ts +12 -4
  87. package/plugins/publishings/threads-pub/dist/index.js +39 -24
  88. package/plugins/publishings/threads-pub/dist/profile-check.js +30 -24
  89. package/plugins/publishings/threads-pub/src/post-rail.ts +20 -0
  90. package/plugins/publishings/wechatmp-pub/dist/index.js +438 -102
  91. package/plugins/publishings/wechatmp-pub/dist/profile-check.js +30 -25
  92. package/plugins/publishings/wechatmp-pub/src/enrich.ts +56 -10
  93. package/plugins/publishings/wechatmp-pub/src/flow.ts +589 -83
  94. package/plugins/publishings/wechatmp-pub/src/index.ts +4 -1
  95. package/plugins/publishings/wechatmp-pub/src/modes.ts +30 -12
  96. package/plugins/publishings/wechatmp-pub/src/page.ts +8 -0
  97. package/plugins/publishings/weibo-pub/dist/index.js +25 -24
  98. package/plugins/publishings/weibo-pub/dist/profile-check.js +25 -24
  99. package/plugins/publishings/x-pub/dist/index.js +54 -47
  100. package/plugins/publishings/x-pub/dist/profile-check.js +25 -24
  101. package/plugins/publishings/x-pub/src/post-rail.ts +40 -47
  102. package/plugins/publishings/xhs-pub/dist/index.js +25 -24
  103. package/plugins/publishings/xhs-pub/dist/profile-check.js +25 -24
  104. package/plugins/publishings/xiaoyuzhou-pub/dist/index.js +25 -24
  105. package/plugins/publishings/xiaoyuzhou-pub/dist/profile-check.js +25 -24
  106. package/plugins/publishings/zenn-pub/dist/index.js +9 -9
@@ -4845,7 +4845,7 @@ var init_zod = __esm(() => {
4845
4845
  init_external();
4846
4846
  });
4847
4847
 
4848
- // ../../node_modules/.bun/@gobing-ai+ts-utils@0.5.32/node_modules/@gobing-ai/ts-utils/dist/errors.js
4848
+ // ../../node_modules/.bun/@gobing-ai+ts-utils@0.8.4/node_modules/@gobing-ai/ts-utils/dist/errors.js
4849
4849
  var ErrorCode;
4850
4850
  var init_errors3 = __esm(() => {
4851
4851
  ErrorCode = {
@@ -4856,7 +4856,7 @@ var init_errors3 = __esm(() => {
4856
4856
  };
4857
4857
  });
4858
4858
 
4859
- // ../../node_modules/.bun/@gobing-ai+ts-utils@0.5.32/node_modules/@gobing-ai/ts-utils/dist/api-response.js
4859
+ // ../../node_modules/.bun/@gobing-ai+ts-utils@0.8.4/node_modules/@gobing-ai/ts-utils/dist/api-response.js
4860
4860
  var API_ERROR_CODES, ERROR_CODE_TO_HTTP, CLIENT_SAFE_CODES;
4861
4861
  var init_api_response = __esm(() => {
4862
4862
  init_errors3();
@@ -4879,10 +4879,10 @@ var init_api_response = __esm(() => {
4879
4879
  CLIENT_SAFE_CODES = new Set([ErrorCode.NotFound, ErrorCode.Validation, ErrorCode.Conflict]);
4880
4880
  });
4881
4881
 
4882
- // ../../node_modules/.bun/@gobing-ai+ts-utils@0.5.32/node_modules/@gobing-ai/ts-utils/dist/cursor.js
4882
+ // ../../node_modules/.bun/@gobing-ai+ts-utils@0.8.4/node_modules/@gobing-ai/ts-utils/dist/cursor.js
4883
4883
  var init_cursor = () => {};
4884
4884
 
4885
- // ../../node_modules/.bun/@gobing-ai+ts-utils@0.5.32/node_modules/@gobing-ai/ts-utils/dist/env.js
4885
+ // ../../node_modules/.bun/@gobing-ai+ts-utils@0.8.4/node_modules/@gobing-ai/ts-utils/dist/env.js
4886
4886
  function getEnvVar(name, fallback) {
4887
4887
  const raw = process.env[name];
4888
4888
  return raw === undefined ? fallback : raw;
@@ -4891,10 +4891,10 @@ function getEnvVars() {
4891
4891
  return process.env;
4892
4892
  }
4893
4893
 
4894
- // ../../node_modules/.bun/@gobing-ai+ts-utils@0.5.32/node_modules/@gobing-ai/ts-utils/dist/event-severity.js
4894
+ // ../../node_modules/.bun/@gobing-ai+ts-utils@0.8.4/node_modules/@gobing-ai/ts-utils/dist/event-severity.js
4895
4895
  var init_event_severity = () => {};
4896
4896
 
4897
- // ../../node_modules/.bun/@gobing-ai+ts-utils@0.5.32/node_modules/@gobing-ai/ts-utils/dist/object.js
4897
+ // ../../node_modules/.bun/@gobing-ai+ts-utils@0.8.4/node_modules/@gobing-ai/ts-utils/dist/object.js
4898
4898
  function isPlainObject2(value) {
4899
4899
  return typeof value === "object" && value !== null && !Array.isArray(value);
4900
4900
  }
@@ -4912,7 +4912,7 @@ function deepMerge(target, source) {
4912
4912
  return result;
4913
4913
  }
4914
4914
 
4915
- // ../../node_modules/.bun/@gobing-ai+ts-utils@0.5.32/node_modules/@gobing-ai/ts-utils/dist/output.js
4915
+ // ../../node_modules/.bun/@gobing-ai+ts-utils@0.8.4/node_modules/@gobing-ai/ts-utils/dist/output.js
4916
4916
  function processStream(name) {
4917
4917
  const proc = globalThis.process;
4918
4918
  const stream = proc?.[name];
@@ -4933,7 +4933,7 @@ function echoError(message, target = defaultStderrTarget ?? processStream("stder
4933
4933
  }
4934
4934
  var defaultStdoutTarget, defaultStderrTarget;
4935
4935
 
4936
- // ../../node_modules/.bun/@gobing-ai+ts-utils@0.5.32/node_modules/@gobing-ai/ts-utils/dist/index.js
4936
+ // ../../node_modules/.bun/@gobing-ai+ts-utils@0.8.4/node_modules/@gobing-ai/ts-utils/dist/index.js
4937
4937
  var init_dist = __esm(() => {
4938
4938
  init_api_response();
4939
4939
  init_cursor();
@@ -11931,7 +11931,7 @@ var init_dist2 = __esm(() => {
11931
11931
  $visitAsync = visit.visitAsync;
11932
11932
  });
11933
11933
 
11934
- // ../../node_modules/.bun/@gobing-ai+ts-runtime@0.5.32+180a6e424da77181/node_modules/@gobing-ai/ts-runtime/dist/config.js
11934
+ // ../../node_modules/.bun/@gobing-ai+ts-runtime@0.8.4+b85a65bb895e3074/node_modules/@gobing-ai/ts-runtime/dist/config.js
11935
11935
  function getProcessEnv() {
11936
11936
  return getEnvVars();
11937
11937
  }
@@ -12009,7 +12009,7 @@ var init_config = __esm(() => {
12009
12009
  };
12010
12010
  });
12011
12011
 
12012
- // ../../node_modules/.bun/@gobing-ai+ts-runtime@0.5.32+180a6e424da77181/node_modules/@gobing-ai/ts-runtime/dist/file-system-node.js
12012
+ // ../../node_modules/.bun/@gobing-ai+ts-runtime@0.8.4+b85a65bb895e3074/node_modules/@gobing-ai/ts-runtime/dist/file-system-node.js
12013
12013
  import { appendFileSync, cpSync, createReadStream, createWriteStream, existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from "fs";
12014
12014
  import { dirname, resolve as resolvePath } from "path";
12015
12015
  function createNodeFileSystem(root, paths) {
@@ -12096,7 +12096,7 @@ function findProjectRoot(startDir) {
12096
12096
  }
12097
12097
  var init_file_system_node = () => {};
12098
12098
 
12099
- // ../../node_modules/.bun/@gobing-ai+ts-runtime@0.5.32+180a6e424da77181/node_modules/@gobing-ai/ts-runtime/dist/db-errors.js
12099
+ // ../../node_modules/.bun/@gobing-ai+ts-runtime@0.8.4+b85a65bb895e3074/node_modules/@gobing-ai/ts-runtime/dist/db-errors.js
12100
12100
  var DbModuleNotInstalledError;
12101
12101
  var init_db_errors = __esm(() => {
12102
12102
  DbModuleNotInstalledError = class DbModuleNotInstalledError extends Error {
@@ -19307,7 +19307,7 @@ var init_execa = __esm(() => {
19307
19307
  } = getIpcExport());
19308
19308
  });
19309
19309
 
19310
- // ../../node_modules/.bun/@gobing-ai+ts-runtime@0.5.32+180a6e424da77181/node_modules/@gobing-ai/ts-runtime/dist/process-group.js
19310
+ // ../../node_modules/.bun/@gobing-ai+ts-runtime@0.8.4+b85a65bb895e3074/node_modules/@gobing-ai/ts-runtime/dist/process-group.js
19311
19311
  function resolveDeadline(optionTimeout, defaultTimeout) {
19312
19312
  if (optionTimeout === null)
19313
19313
  return null;
@@ -19399,7 +19399,7 @@ function ownProcessGroupLifecycle(ownership) {
19399
19399
  }
19400
19400
  var MAX_TIMEOUT_MS = 2147483647, DEFAULT_KILL_GRACE_MS = 5000, GROUP_POLL_INTERVAL_MS = 25, GROUP_KILL_PATIENCE_MS = 2000;
19401
19401
 
19402
- // ../../node_modules/.bun/@gobing-ai+ts-runtime@0.5.32+180a6e424da77181/node_modules/@gobing-ai/ts-runtime/dist/process-executor.js
19402
+ // ../../node_modules/.bun/@gobing-ai+ts-runtime@0.8.4+b85a65bb895e3074/node_modules/@gobing-ai/ts-runtime/dist/process-executor.js
19403
19403
  import { isatty } from "tty";
19404
19404
  function processEventSeverity(reason, exitCode) {
19405
19405
  if (reason === "error")
@@ -19771,7 +19771,7 @@ var init_process_executor = __esm(() => {
19771
19771
  init_config();
19772
19772
  });
19773
19773
 
19774
- // ../../node_modules/.bun/@gobing-ai+ts-runtime@0.5.32+180a6e424da77181/node_modules/@gobing-ai/ts-runtime/dist/runtime-node-bun.js
19774
+ // ../../node_modules/.bun/@gobing-ai+ts-runtime@0.8.4+b85a65bb895e3074/node_modules/@gobing-ai/ts-runtime/dist/runtime-node-bun.js
19775
19775
  function getNodeFileSystem() {
19776
19776
  if (!_nodeFileSystem)
19777
19777
  _nodeFileSystem = createNodeFileSystem();
@@ -20099,11 +20099,11 @@ var PluginManifestSchema = PluginManifestSchemaBase.superRefine((manifest, ctx)
20099
20099
  });
20100
20100
  }
20101
20101
  });
20102
- // ../../node_modules/.bun/@gobing-ai+ts-runtime@0.5.32+180a6e424da77181/node_modules/@gobing-ai/ts-runtime/dist/index.js
20102
+ // ../../node_modules/.bun/@gobing-ai+ts-runtime@0.8.4+b85a65bb895e3074/node_modules/@gobing-ai/ts-runtime/dist/index.js
20103
20103
  init_file_system_node();
20104
20104
  init_config();
20105
20105
 
20106
- // ../../node_modules/.bun/@gobing-ai+ts-runtime@0.5.32+180a6e424da77181/node_modules/@gobing-ai/ts-runtime/dist/path.js
20106
+ // ../../node_modules/.bun/@gobing-ai+ts-runtime@0.8.4+b85a65bb895e3074/node_modules/@gobing-ai/ts-runtime/dist/path.js
20107
20107
  function normalizeSeparators(path) {
20108
20108
  return path.replaceAll("\\", "/");
20109
20109
  }
@@ -20161,7 +20161,7 @@ function getProcessCwd() {
20161
20161
  return globalThis.process?.cwd?.() ?? "/";
20162
20162
  }
20163
20163
 
20164
- // ../../node_modules/.bun/@gobing-ai+ts-runtime@0.5.32+180a6e424da77181/node_modules/@gobing-ai/ts-runtime/dist/index.js
20164
+ // ../../node_modules/.bun/@gobing-ai+ts-runtime@0.8.4+b85a65bb895e3074/node_modules/@gobing-ai/ts-runtime/dist/index.js
20165
20165
  init_runtime_node_bun();
20166
20166
 
20167
20167
  // ../../packages/kk-core/src/render-md.ts
@@ -20254,7 +20254,7 @@ async function trySelectors(page, selectors, options = {}) {
20254
20254
  import { join as join5, resolve as resolve5 } from "path";
20255
20255
  import { parseArgs } from "util";
20256
20256
 
20257
- // ../../node_modules/.bun/@gobing-ai+ts-browser-automation@0.5.32+0f5f0476d0d466a6/node_modules/@gobing-ai/ts-browser-automation/dist/errors.js
20257
+ // ../../node_modules/.bun/@gobing-ai+ts-browser-automation@0.8.4+7a0bf9ce62a9b753/node_modules/@gobing-ai/ts-browser-automation/dist/errors.js
20258
20258
  class BrowserAutomationError extends Error {
20259
20259
  constructor(message, options) {
20260
20260
  super(message, options);
@@ -20303,10 +20303,10 @@ class OperationAbortedError extends BrowserAutomationError {
20303
20303
  this.name = "OperationAbortedError";
20304
20304
  }
20305
20305
  }
20306
- // ../../node_modules/.bun/@gobing-ai+ts-browser-automation@0.5.32+0f5f0476d0d466a6/node_modules/@gobing-ai/ts-browser-automation/dist/launcher.js
20306
+ // ../../node_modules/.bun/@gobing-ai+ts-browser-automation@0.8.4+7a0bf9ce62a9b753/node_modules/@gobing-ai/ts-browser-automation/dist/launcher.js
20307
20307
  import { mkdir } from "fs/promises";
20308
20308
 
20309
- // ../../node_modules/.bun/@gobing-ai+ts-browser-automation@0.5.32+0f5f0476d0d466a6/node_modules/@gobing-ai/ts-browser-automation/dist/profile-dir.js
20309
+ // ../../node_modules/.bun/@gobing-ai+ts-browser-automation@0.8.4+7a0bf9ce62a9b753/node_modules/@gobing-ai/ts-browser-automation/dist/profile-dir.js
20310
20310
  function resolveProfileDir(profileDir) {
20311
20311
  if (profileDir.trim() === "") {
20312
20312
  throw new InvalidProfileDirError;
@@ -20318,7 +20318,7 @@ function resolveProfileDir(profileDir) {
20318
20318
  return resolved;
20319
20319
  }
20320
20320
 
20321
- // ../../node_modules/.bun/@gobing-ai+ts-browser-automation@0.5.32+0f5f0476d0d466a6/node_modules/@gobing-ai/ts-browser-automation/dist/launcher.js
20321
+ // ../../node_modules/.bun/@gobing-ai+ts-browser-automation@0.8.4+7a0bf9ce62a9b753/node_modules/@gobing-ai/ts-browser-automation/dist/launcher.js
20322
20322
  var PROFILE_DIR_MODE = 448;
20323
20323
  var BUSY_PROFILE_PATTERN = /singleton|already in use|in use by another/i;
20324
20324
  var CHROMIUM_MISSING_PATTERN = /playwright install|executable doesn't exist/i;
@@ -20369,7 +20369,7 @@ function createPersistentLauncher(options = {}) {
20369
20369
  };
20370
20370
  }
20371
20371
 
20372
- // ../../node_modules/.bun/@gobing-ai+ts-browser-automation@0.5.32+0f5f0476d0d466a6/node_modules/@gobing-ai/ts-browser-automation/dist/operations.js
20372
+ // ../../node_modules/.bun/@gobing-ai+ts-browser-automation@0.8.4+7a0bf9ce62a9b753/node_modules/@gobing-ai/ts-browser-automation/dist/operations.js
20373
20373
  var DEFAULT_TIMEOUT_MS = 30000;
20374
20374
  var POLL_INTERVAL_MS = 250;
20375
20375
  var defaultLauncher;
@@ -20698,7 +20698,8 @@ async function busyGuidance(fileSystem, leaseDir) {
20698
20698
  }
20699
20699
  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
20700
  }
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`;
20701
+ const suffix = 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 \u2014 confirm no browser for this profile is open, then remove the stale lease with: rm -rf ${leaseDir}`;
20702
+ return `browser lease ${leaseDir} is held by pid ${owner.pid} (logical ${owner.logicalPath}) \u2014 ${suffix}`;
20702
20703
  }
20703
20704
  async function holderResidue(fileSystem, leaseDir) {
20704
20705
  try {
@@ -20934,7 +20935,7 @@ function resolveChannelProfileDir(channel, override) {
20934
20935
  return resolveBrowserProfileDir(channel, chosen);
20935
20936
  }
20936
20937
  async function checkChannelSession(config, opts) {
20937
- const timeoutMs = opts.timeoutMs ?? DEFAULT_CHECK_TIMEOUT_MS;
20938
+ const timeoutMs = opts.timeoutMs ?? config.checkTimeoutMs ?? DEFAULT_CHECK_TIMEOUT_MS;
20938
20939
  const passes = opts.headedOnly ? [false] : opts.headedFallback === false ? [true] : [true, false];
20939
20940
  let lastDetail = `${config.channel} readiness was never probed`;
20940
20941
  const deadline = Date.now() + timeoutMs;
@@ -21267,7 +21268,7 @@ function editorTextScript(selector) {
21267
21268
  init_dist();
21268
21269
 
21269
21270
  // ../../plugins/publishings/wechatmp-pub/src/flow.ts
21270
- import { randomUUID } from "crypto";
21271
+ import { createHash as createHash2, randomUUID } from "crypto";
21271
21272
  import { tmpdir } from "os";
21272
21273
  import { extname, join as join6 } from "path";
21273
21274
 
@@ -21697,6 +21698,10 @@ async function resolveMediaPath(content, spec) {
21697
21698
  }
21698
21699
  return { path };
21699
21700
  }
21701
+ function isLibraryCover(content) {
21702
+ const wechatmp = content.metadata?.wechatmp;
21703
+ return typeof wechatmp === "object" && wechatmp !== null && !Array.isArray(wechatmp) && wechatmp.coverSource === "library";
21704
+ }
21700
21705
  async function resolveBodyImages(content) {
21701
21706
  const ordered = content.metadata?.images;
21702
21707
  if (ordered !== undefined && !Array.isArray(ordered)) {
@@ -21706,20 +21711,22 @@ async function resolveBodyImages(content) {
21706
21711
  const cover = typeof content.metadata?.wechatmp === "object" && content.metadata.wechatmp !== null ? content.metadata.wechatmp.coverPath : undefined;
21707
21712
  const candidates = [];
21708
21713
  if (typeof cover === "string" && cover.length > 0)
21709
- candidates.push({ path: cover, what: "metadata.wechatmp.coverPath" });
21714
+ candidates.push({ path: cover, what: "metadata.wechatmp.coverPath", coverOnly: true });
21710
21715
  const genericCover = content.metadata?.coverImage;
21711
21716
  const genericCoverPath = typeof genericCover === "string" ? genericCover : typeof genericCover?.path === "string" ? genericCover.path : undefined;
21712
21717
  if (genericCoverPath !== undefined && genericCoverPath.length > 0)
21713
- candidates.push({ path: genericCoverPath, what: "metadata.coverImage" });
21718
+ candidates.push({ path: genericCoverPath, what: "metadata.coverImage", coverOnly: true });
21714
21719
  for (const [index, image] of descriptors.entries()) {
21715
21720
  const path = typeof image === "string" ? image : image?.path;
21716
21721
  if (typeof path !== "string" || path.length === 0) {
21717
21722
  return { error: `images validation: images[${index}] carries no path` };
21718
21723
  }
21719
- candidates.push({ path, what: `metadata.images[${index}]` });
21724
+ candidates.push({ path, what: `metadata.images[${index}]`, coverOnly: false });
21720
21725
  }
21726
+ const skipCoverInBody = isLibraryCover(content);
21721
21727
  const paths = [];
21722
- for (const { path, what } of candidates) {
21728
+ let hasValidatedCover = false;
21729
+ for (const { path, what, coverOnly } of candidates) {
21723
21730
  if (!isAbsolute2(path)) {
21724
21731
  return { error: `images validation: ${what} must be absolute, got '${path}'` };
21725
21732
  }
@@ -21731,9 +21738,12 @@ async function resolveBodyImages(content) {
21731
21738
  if (!await createNodeFileSystem().exists(path)) {
21732
21739
  return { error: `images validation: ${what} does not exist: '${path}'` };
21733
21740
  }
21734
- paths.push(path);
21741
+ if (coverOnly)
21742
+ hasValidatedCover = true;
21743
+ if (!(skipCoverInBody && coverOnly))
21744
+ paths.push(path);
21735
21745
  }
21736
- return { paths };
21746
+ return { paths, hasValidatedCover };
21737
21747
  }
21738
21748
  function deriveDigest(content) {
21739
21749
  const explicit = content.metadata?.digest;
@@ -21811,7 +21821,7 @@ async function validateModeInput(operation, content) {
21811
21821
  const images = await resolveBodyImages(content);
21812
21822
  if (images.error)
21813
21823
  return { error: images.error };
21814
- if ((images.paths ?? []).length === 0) {
21824
+ if ((images.paths ?? []).length === 0 && !(isLibraryCover(content) && images.hasValidatedCover === true)) {
21815
21825
  return {
21816
21826
  error: "cover validation: \u6587\u7AE0 takes its cover from a body image (\u9ED8\u8BA4\u9996\u56FE\u4E3A\u5C01\u9762) but none was supplied \u2014 set metadata.wechatmp.coverPath, metadata.coverImage or metadata.images[]"
21817
21827
  };
@@ -22656,6 +22666,9 @@ function wrapPlaywrightPage(raw) {
22656
22666
  }
22657
22667
  }),
22658
22668
  setInputFiles: (selector, paths) => pw.setInputFiles(selector, paths),
22669
+ screenshot: async (path) => {
22670
+ await raw.screenshot({ path });
22671
+ },
22659
22672
  url: () => pw.url(),
22660
22673
  evaluate: (expression) => pw.evaluate(expression),
22661
22674
  waitForTimeout: (ms) => pw.waitForTimeout(ms),
@@ -22733,7 +22746,11 @@ var URL_COMMITTED = `(() => {
22733
22746
  return checkbox?.checked === true ? area.querySelector('.article_url_setting')?.textContent ?? null : null;
22734
22747
  })()`;
22735
22748
  var ORIGINAL_DECLARATION = `${DIALOG} label:has(.js_original_type_radio):has-text("\u6587\u5B57\u539F\u521B")`;
22736
- var ORIGINAL_AGREEMENT = `${DIALOG} label.original_agreement:has(input[type="checkbox"]:not(:checked))`;
22749
+ var ORIGINAL_AGREEMENT = [
22750
+ `${DIALOG} label.original_agreement:has(input[type="checkbox"]:not(:checked))`,
22751
+ `${DIALOG} label:has(input[type="checkbox"]:not(:checked)):has-text("\u6211\u5DF2\u9605\u8BFB\u5E76\u540C\u610F") i.weui-desktop-icon-checkbox`,
22752
+ `${DIALOG} label:has(input[type="checkbox"]:not(:checked)):has-text("\u6211\u5DF2\u9605\u8BFB\u5E76\u540C\u610F")`
22753
+ ];
22737
22754
  var COLLECTION_SETTLE_MS = 1200;
22738
22755
  var STEP_RETRY_SETTLE_MS = 1000;
22739
22756
  var SWEEP_SETTLE_MS = 400;
@@ -22745,6 +22762,12 @@ function norm(value) {
22745
22762
  }
22746
22763
  var COMMITTED = {
22747
22764
  original: `(() => {
22765
+ const open = document.querySelector('#js_original_open');
22766
+ if (open) {
22767
+ if (open.getClientRects().length === 0) return false;
22768
+ const sw = open.querySelector('input.weui-desktop-switch__input, input[type="checkbox"]');
22769
+ return sw ? sw.checked === true : true;
22770
+ }
22748
22771
  const el = [...document.querySelectorAll('#js_original input.weui-desktop-switch__input')]
22749
22772
  .find(input => input.parentElement?.getClientRects().length > 0);
22750
22773
  return el ? el.checked === true : null;
@@ -22806,8 +22829,9 @@ async function readChecked(page, expression) {
22806
22829
  return null;
22807
22830
  }
22808
22831
  }
22809
- async function enrichArticle(page, meta) {
22832
+ async function enrichArticleDetailed(page, meta) {
22810
22833
  const warnings = [];
22834
+ const capabilityWarnings = [];
22811
22835
  const str = (key) => typeof meta[key] === "string" ? meta[key] : "";
22812
22836
  const on = (key) => meta[key] === true;
22813
22837
  const sweep = async () => {
@@ -22849,7 +22873,9 @@ async function enrichArticle(page, meta) {
22849
22873
  return "ok";
22850
22874
  } catch (error) {
22851
22875
  if (error instanceof CapabilityError) {
22852
- warnings.push(`${name}: ${error.message}`);
22876
+ const msg = `${name}: ${error.message}`;
22877
+ warnings.push(msg);
22878
+ capabilityWarnings.push(msg);
22853
22879
  return "capability";
22854
22880
  }
22855
22881
  }
@@ -22877,11 +22903,14 @@ async function enrichArticle(page, meta) {
22877
22903
  const outcome = await step(name, async () => {
22878
22904
  await openRow(ROW_ORIGINAL, "\u539F\u521B\u58F0\u660E");
22879
22905
  await clickSelector(page, ORIGINAL_DECLARATION, 5000);
22880
- const agreement = await trySelectors(page, [ORIGINAL_AGREEMENT]);
22881
- if (agreement.found) {
22882
- await clickSelector(page, ORIGINAL_AGREEMENT, 3000);
22906
+ const agreement = await trySelectors(page, ORIGINAL_AGREEMENT);
22907
+ if (agreement.found && agreement.selector != null) {
22908
+ await clickSelector(page, agreement.selector, 3000);
22883
22909
  }
22884
22910
  await clickSelector(page, ORIGINAL_CONFIRM, 8000);
22911
+ await page.locator(DIALOG).first().waitFor?.({ state: "hidden", timeout: 1500 }).catch(() => {
22912
+ return;
22913
+ });
22885
22914
  });
22886
22915
  if (outcome !== "capability" && await readChecked(page, COMMITTED.original) !== true && !await residual(name)) {
22887
22916
  warnings.push(`${name}: \u539F\u521B\u58F0\u660E\u672A\u751F\u6548\uFF0C\u8BF7\u624B\u52A8\u8BBE\u7F6E`);
@@ -22947,7 +22976,9 @@ async function enrichArticle(page, meta) {
22947
22976
  };
22948
22977
  const urlRow = await readUrl() === norm(originalUrl) ? "committed" : await tryFindSelector(page, ROW_URL, 2000);
22949
22978
  if (urlRow === undefined) {
22950
- warnings.push(`${name}: \u884C\u4E0D\u5B58\u5728\uFF08\u5F53\u524D\u516C\u4F17\u53F7\u4E0D\u652F\u6301\uFF09\uFF0C\u8BF7\u624B\u52A8\u5904\u7406\u6216\u79FB\u9664 originalUrl`);
22979
+ const msg = `${name}: \u884C\u4E0D\u5B58\u5728\uFF08\u5F53\u524D\u516C\u4F17\u53F7\u4E0D\u652F\u6301\uFF09\uFF0C\u8BF7\u624B\u52A8\u5904\u7406\u6216\u79FB\u9664 originalUrl`;
22980
+ warnings.push(msg);
22981
+ capabilityWarnings.push(msg);
22951
22982
  } else if (urlRow !== "committed") {
22952
22983
  await step(name, async () => {
22953
22984
  if (await readUrl() === norm(originalUrl))
@@ -22999,7 +23030,14 @@ async function enrichArticle(page, meta) {
22999
23030
  }
23000
23031
  }
23001
23032
  await sweep();
23002
- return warnings;
23033
+ const ranAfterOriginal = on("reward") || collection !== "" || originalUrl !== "" || claimSource !== "";
23034
+ const hadOriginalWarning = warnings.some((w) => w.startsWith("\u539F\u521B\u58F0\u660E:"));
23035
+ if (on("original") && ranAfterOriginal && !hadOriginalWarning) {
23036
+ if (await readChecked(page, COMMITTED.original) === false) {
23037
+ warnings.push("\u539F\u521B\u58F0\u660E: \u540E\u7EED\u8BBE\u7F6E\u540E\u539F\u521B\u58F0\u660E\u88AB\u91CD\u7F6E\uFF0C\u8BF7\u6838\u5BF9");
23038
+ }
23039
+ }
23040
+ return { warnings, capabilityWarnings };
23003
23041
  }
23004
23042
 
23005
23043
  // ../../plugins/publishings/wechatmp-pub/src/flow.ts
@@ -23064,6 +23102,8 @@ var COVER_CONFIRM = [
23064
23102
  var DIALOG_DISMISS = [
23065
23103
  '.weui-desktop-dialog:visible button:has-text("\u53D6\u6D88")',
23066
23104
  ".weui-desktop-dialog__close",
23105
+ '.weui-desktop-dialog__wrp button:has-text("\u6211\u77E5\u9053\u4E86")',
23106
+ 'button:has-text("\u6211\u77E5\u9053\u4E86")',
23067
23107
  'button:has-text("\u53D6\u6D88")'
23068
23108
  ];
23069
23109
  async function dismissOpenDialog(page) {
@@ -23083,7 +23123,11 @@ var DIALOG_CLOSE = [
23083
23123
  ".weui-desktop-dialog__close",
23084
23124
  ".weui-desktop-dialog__close-btn",
23085
23125
  '.weui-desktop-dialog__wrp button:has-text("\u53D6\u6D88")',
23086
- 'button:has-text("\u53D6\u6D88")'
23126
+ 'button:has-text("\u53D6\u6D88")',
23127
+ '.weui-desktop-dialog__wrp button:has-text("\u6211\u77E5\u9053\u4E86")',
23128
+ 'button:has-text("\u6211\u77E5\u9053\u4E86")',
23129
+ '.weui-desktop-dialog__wrp button:has-text("\u5173\u95ED")',
23130
+ '.weui-desktop-dialog__wrp button:has-text("\u786E\u5B9A")'
23087
23131
  ];
23088
23132
  async function closeOpenDialogs(page) {
23089
23133
  for (let pass = 0;pass < 3; pass += 1) {
@@ -23331,6 +23375,16 @@ async function enterMode(deps, operation) {
23331
23375
  async function attachImages(page, images, deps) {
23332
23376
  const selector = await findAttachedSelector(page, IMAGE_FILE_INPUT, "image file input", deps.stepTimeoutMs);
23333
23377
  await page.setInputFiles(selector, images);
23378
+ if (images.length === 0)
23379
+ return;
23380
+ await closeOpenDialogs(page);
23381
+ const bodySelector = await findSelector(page, BODY_BLOCK, "article body", deps.stepTimeoutMs);
23382
+ const countScript = `/* __KK_WECHAT_BODY_IMAGE_COUNT__ */ [...document.querySelectorAll(${JSON.stringify(`${bodySelector} img`)})].filter((img) => /^https?:/.test(img.currentSrc || img.src)).length`;
23383
+ const uploadTimeoutMs = Math.min(Math.max(deps.stepTimeoutMs, 45000), 60000);
23384
+ const landed = await waitUntil(async () => Number(await page.evaluate(countScript).catch(() => 0)) >= images.length, uploadTimeoutMs, 250);
23385
+ if (!landed) {
23386
+ 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`);
23387
+ }
23334
23388
  }
23335
23389
  async function typeTitle(page, deps) {
23336
23390
  const title = titleOf(deps.content);
@@ -23362,15 +23416,139 @@ async function readTitleMirror(page) {
23362
23416
  return { observed: false, value: "" };
23363
23417
  }
23364
23418
  }
23419
+ async function inlineFiguresOf(content) {
23420
+ const raw = content.metadata?.wechatmp?.inlineFigures;
23421
+ if (raw === undefined)
23422
+ return [];
23423
+ if (!Array.isArray(raw) || raw.length === 0)
23424
+ return [];
23425
+ const figures = [];
23426
+ for (const [index, entry] of raw.entries()) {
23427
+ const figure = entry ?? {};
23428
+ const id = `figure-${index + 1}`;
23429
+ for (const field of ["id", "path", "sha256", "altText", "caption"]) {
23430
+ if (typeof figure[field] !== "string" || String(figure[field]).trim() === "") {
23431
+ throw new Error(`inline figures: ${id} metadata has no ${field} \u2014 refusing to place an unverified figure`);
23432
+ }
23433
+ }
23434
+ if (figure.id !== id) {
23435
+ throw new Error(`inline figures: expected id '${id}' at position ${index + 1}, found '${String(figure.id)}' \u2014 figure order is the body order`);
23436
+ }
23437
+ const path = String(figure.path);
23438
+ const expected = String(figure.sha256);
23439
+ let actual;
23440
+ try {
23441
+ actual = createHash2("sha256").update((await readLocalImageBytes(path)).bytes).digest("hex");
23442
+ } catch {
23443
+ throw new Error(`inline figures: ${id} image is unreadable at ${path} \u2014 refusing to publish a missing figure`);
23444
+ }
23445
+ if (actual !== expected) {
23446
+ throw new Error(`inline figures: ${id} image bytes changed since the review (${path}) \u2014 re-render before publishing`);
23447
+ }
23448
+ figures.push({
23449
+ id,
23450
+ path,
23451
+ sha256: expected,
23452
+ altText: String(figure.altText),
23453
+ caption: String(figure.caption)
23454
+ });
23455
+ }
23456
+ return figures;
23457
+ }
23458
+ function assertInlineFigureMarkers(body, figures) {
23459
+ const found = [...body.matchAll(/!\[[^\]]*\]\(kk-inline:([^)]+)\)/g)].map((match) => String(match[1]));
23460
+ const expected = figures.map((figure) => figure.id);
23461
+ if (found.length !== expected.length) {
23462
+ 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`);
23463
+ }
23464
+ for (const [index, id] of expected.entries()) {
23465
+ if (found[index] !== id) {
23466
+ 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`);
23467
+ }
23468
+ }
23469
+ }
23470
+ function escapeFigureText(value) {
23471
+ return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;");
23472
+ }
23473
+ function withInlineFigureHtml(body, figures, srcs) {
23474
+ if (srcs.length !== figures.length) {
23475
+ 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`);
23476
+ }
23477
+ let out = body;
23478
+ for (const [index, figure] of figures.entries()) {
23479
+ const marker = new RegExp(`!\\[[^\\]]*\\]\\(kk-inline:${figure.id}\\)`);
23480
+ if (!marker.test(out)) {
23481
+ throw new Error(`inline figures: ${figure.id} marker is missing from the body \u2014 refusing to insert`);
23482
+ }
23483
+ const src = String(srcs[index]);
23484
+ const html = `<img src="${escapeFigureText(src)}" alt="${escapeFigureText(figure.altText)}" data-kk-figure="${figure.id}"><p>${escapeFigureText(figure.caption)}</p>`;
23485
+ out = out.replace(marker, () => html);
23486
+ }
23487
+ return out;
23488
+ }
23489
+ async function bodyImageSrcs(page, selectors) {
23490
+ const script = `(() => {
23491
+ const el = ${JSON.stringify(selectors)}.map((s) => document.querySelector(s)).find(Boolean);
23492
+ if (!el) return [];
23493
+ return Array.from(el.querySelectorAll('img')).map((img) => img.getAttribute('src') || '').filter(Boolean);
23494
+ })()`;
23495
+ const raw = await page.evaluate(script).catch(() => []);
23496
+ return Array.isArray(raw) ? raw.map((value) => String(value)) : [];
23497
+ }
23498
+ async function waitForInlineFigureSrcs(page, count, deps) {
23499
+ const deadline = Date.now() + deps.stepTimeoutMs;
23500
+ let srcs = [];
23501
+ while (Date.now() < deadline) {
23502
+ srcs = await bodyImageSrcs(page, BODY_BLOCK);
23503
+ if (srcs.length >= count)
23504
+ return srcs.slice(-count);
23505
+ await new Promise((resolve) => setTimeout(resolve, 200));
23506
+ }
23507
+ 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`);
23508
+ }
23509
+ async function verifyInlineFigureDom(page, selectors, figures, srcs) {
23510
+ const script = `(() => {
23511
+ const el = ${JSON.stringify(selectors)}.map((s) => document.querySelector(s)).find(Boolean);
23512
+ if (!el) return [];
23513
+ return Array.from(el.querySelectorAll('img[data-kk-figure]')).map((img) => ({
23514
+ id: img.getAttribute('data-kk-figure') || '',
23515
+ src: img.getAttribute('src') || '',
23516
+ alt: img.getAttribute('alt') || '',
23517
+ caption: (img.nextElementSibling && img.nextElementSibling.textContent) || '',
23518
+ }));
23519
+ })()`;
23520
+ const observed = await page.evaluate(script).catch(() => []);
23521
+ if (!Array.isArray(observed) || observed.length !== figures.length) {
23522
+ 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)`);
23523
+ }
23524
+ for (const [index, figure] of figures.entries()) {
23525
+ const seen = observed[index];
23526
+ if (seen === undefined || seen.id !== figure.id) {
23527
+ throw new Error(`inline figures: editor position ${index + 1} holds '${String(seen?.id)}', expected '${figure.id}'`);
23528
+ }
23529
+ if (seen.src !== String(srcs[index])) {
23530
+ throw new Error(`inline figures: ${figure.id} shows '${seen.src}', expected '${String(srcs[index])}'`);
23531
+ }
23532
+ if (seen.alt !== figure.altText) {
23533
+ throw new Error(`inline figures: ${figure.id} alt text reads '${seen.alt}', expected '${figure.altText}'`);
23534
+ }
23535
+ if (seen.caption.trim() !== figure.caption.trim()) {
23536
+ throw new Error(`inline figures: ${figure.id} caption reads '${seen.caption.trim()}', expected '${figure.caption}'`);
23537
+ }
23538
+ }
23539
+ }
23365
23540
  async function insertBody(page, deps, selectors = BODY_BLOCK) {
23366
23541
  const body = bodyOf(deps.content);
23367
23542
  if (body.trim().length === 0)
23368
23543
  return;
23544
+ await insertHtmlBody(page, body, markdownToWechatHtml(body), deps, selectors);
23545
+ }
23546
+ async function insertHtmlBody(page, body, html, deps, selectors = BODY_BLOCK) {
23369
23547
  const selector = await findSelector(page, selectors, "article body", deps.stepTimeoutMs);
23370
- const html = markdownToWechatHtml(body);
23371
23548
  try {
23372
23549
  await pasteHtml(asPlaywrightPage(page), selector, html, { timeoutMs: Math.min(deps.stepTimeoutMs, 1e4) });
23373
- return;
23550
+ if (await bodyLength(page, selector) > 0)
23551
+ return;
23374
23552
  } catch {}
23375
23553
  await closeOpenDialogs(page);
23376
23554
  await clickSelector(page, selector, deps.stepTimeoutMs);
@@ -23464,21 +23642,26 @@ function nativeLegacyEditorReadyScript() {
23464
23642
  '#js_save_success, #js_save_success_with_ad, #js_save_success_with_ad_op',
23465
23643
  )];
23466
23644
  if (!autoSaveContainer || !legacyAutoSave || saveSuccessMarkers.length === 0) return 'unknown';
23467
- const hidden = (node) => {
23645
+ let legacyAutoSaveHidden = true;
23646
+ for (const node of [legacyAutoSave, ...saveSuccessMarkers]) {
23468
23647
  const style = window.getComputedStyle(node);
23469
23648
  const rect = node.getBoundingClientRect();
23470
- return style.display === 'none' || style.visibility === 'hidden' || rect.width === 0 || rect.height === 0;
23471
- };
23472
- const visibleSaveControls = [...document.querySelectorAll('button, a')].filter((node) => {
23473
- const text = (node.textContent ?? '').replace(/[\\s\\u00a0]+/g, '').trim();
23474
- if (text !== '\u4FDD\u5B58\u4E3A\u8349\u7A3F') return false;
23649
+ if (!(style.display === 'none' || style.visibility === 'hidden' || rect.width === 0 || rect.height === 0)) {
23650
+ legacyAutoSaveHidden = false;
23651
+ }
23652
+ }
23653
+ const visibleSaveControls = [];
23654
+ for (const node of [...document.querySelectorAll('button, a')]) {
23655
+ const label = (node.textContent ?? '').replace(/[\\s\\u00a0]+/g, '').trim();
23656
+ if (label !== '\u4FDD\u5B58\u4E3A\u8349\u7A3F') continue;
23475
23657
  const style = window.getComputedStyle(node);
23476
23658
  const rect = node.getBoundingClientRect();
23477
- return style.display !== 'none' && style.visibility !== 'hidden' && rect.width > 0 && rect.height > 0;
23478
- });
23659
+ if (style.display !== 'none' && style.visibility !== 'hidden' && rect.width > 0 && rect.height > 0) {
23660
+ visibleSaveControls.push(node);
23661
+ }
23662
+ }
23479
23663
  return autoSaveContainer.textContent?.trim() === '' &&
23480
- hidden(legacyAutoSave) &&
23481
- saveSuccessMarkers.every(hidden) &&
23664
+ legacyAutoSaveHidden &&
23482
23665
  visibleSaveControls.length === 1
23483
23666
  ? 'ready'
23484
23667
  : 'unknown';
@@ -23625,40 +23808,73 @@ async function setCover(page, source, deps, identity) {
23625
23808
  await dismissOpenDialog(page);
23626
23809
  return inventory ? `${message} (dialogs: ${inventory})` : message;
23627
23810
  };
23811
+ 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";
23812
+ const clickSource = async () => {
23813
+ const pick = await tryFindSelector(page, picker, Math.min(deps.stepTimeoutMs, 8000));
23814
+ if (pick !== undefined) {
23815
+ await clickSelector(page, pick, deps.stepTimeoutMs);
23816
+ return true;
23817
+ }
23818
+ return Boolean(await page.evaluate(`/* __KK_WECHAT_DOM_CLICK__ */ (() => {
23819
+ const el = document.querySelector(${JSON.stringify(domPicker)});
23820
+ if (!el) return false;
23821
+ el.click();
23822
+ return true;
23823
+ })()`).catch(() => false));
23824
+ };
23628
23825
  try {
23629
23826
  const open = await tryFindSelector(page, COVER_PANEL_OPEN, Math.min(deps.stepTimeoutMs, 5000));
23630
23827
  if (open === undefined)
23631
23828
  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");
23632
23829
  await clickSelector(page, open, deps.stepTimeoutMs);
23633
23830
  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;
23634
- if (!alreadyOpen) {
23635
- const pick = await tryFindSelector(page, picker, Math.min(deps.stepTimeoutMs, 8000));
23636
- if (pick === undefined)
23637
- return await warn(`cover: ${what} was not offered by the open cover panel`);
23638
- await clickSelector(page, pick, deps.stepTimeoutMs);
23639
- }
23831
+ if (!alreadyOpen && !await clickSource())
23832
+ return await warn(`cover: ${what} was not offered by the open cover panel`);
23640
23833
  if (wanted.length === 0)
23641
23834
  return await warn(`cover: no requested cover file identity to match against \u2014 ${what} not driven`);
23642
23835
  const IDENTIFY = `(() => {
23643
23836
  const wanted = ${JSON.stringify(wanted)};
23644
- 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')]
23837
+ 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')]
23645
23838
  .filter((row) => row.offsetWidth > 0);
23646
- const nameOf = (row) => {
23839
+ const namedRows = [];
23840
+ for (const row of rows) {
23647
23841
  const el = row.querySelector('[title], [data-name], [data-file_name]') ?? row;
23648
23842
  const attrs = [el.getAttribute?.('title'), el.getAttribute?.('data-name'), el.getAttribute?.('data-file_name')];
23649
23843
  const text = [...row.querySelectorAll('[class*="name" i], [class*="title" i]')].map((n) => n.textContent ?? '');
23650
- return [...attrs, ...text].map((v) => (v ?? '').trim()).filter((v) => v.length > 0);
23651
- };
23652
- const hits = rows.filter((row) => wanted.some((w) => nameOf(row).includes(w)));
23653
- if (hits.length === 0) return 'missing';
23654
- if (hits.length > 1) return 'ambiguous';
23655
- const row = hits[0];
23844
+ const names = [...attrs, ...text].map((v) => (v ?? '').trim()).filter((v) => v.length > 0);
23845
+ namedRows.push({ row, names });
23846
+ }
23847
+ const hits = [];
23848
+ for (const entry of namedRows) {
23849
+ if (wanted.some((w) => entry.names.includes(w))) hits.push(entry.row);
23850
+ }
23851
+ // The \u4ECE\u6B63\u6587\u9009\u62E9 picker exposes no filename on the current build: it renders
23852
+ // .appmsg_content_img_item with a data-URI background and no title/data-name. A SOLE
23853
+ // visible IMAGE candidate is therefore uniquely identified by the picker itself; several
23854
+ // anonymous candidates still refuse rather than guessing the first one. The broad
23855
+ // selector list above also matches cover-MENU <li> nodes, which must never be clicked
23856
+ // as if they were images. Plain loops, not new arrow functions, keep the per-file
23857
+ // function-coverage gate honest about page-side code it cannot instrument.
23858
+ const anonymousRows = [];
23859
+ for (const entry of namedRows) {
23860
+ const row = entry.row;
23861
+ const isImage =
23862
+ row.matches('.appmsg_content_img_item, .weui-desktop-img-picker__item') ||
23863
+ row.querySelector('.appmsg_content_img') !== null;
23864
+ // A near-match whose exposed name disagrees is NOT anonymous and still refuses.
23865
+ if (isImage && entry.names.length === 0) anonymousRows.push(row);
23866
+ }
23867
+ const candidates = hits.length > 0 ? hits : anonymousRows.length === 1 ? anonymousRows : [];
23868
+ if (candidates.length === 0) return 'missing';
23869
+ if (candidates.length > 1) return 'ambiguous';
23870
+ const row = candidates[0];
23871
+ const soleCandidate = hits.length === 0;
23656
23872
  if (!row.classList.contains('selected')) row.click();
23657
23873
  const checked = row.querySelector('input[type=checkbox], [role=checkbox]');
23658
23874
  const css = row.querySelector('[style*="background-image"]')?.style.backgroundImage ?? '';
23659
23875
  const backgroundUrl = css.startsWith('url("') || css.startsWith("url('") ? css.slice(5, -2) : css.startsWith('url(') ? css.slice(4, -1) : '';
23660
23876
  const src = row.querySelector('img')?.src || backgroundUrl;
23661
- return JSON.stringify({ picked: true, src });
23877
+ return JSON.stringify({ picked: true, src, soleCandidate });
23662
23878
  })()`;
23663
23879
  let rawIdentify = "missing";
23664
23880
  await waitUntil(async () => {
@@ -23742,13 +23958,27 @@ async function setCover(page, source, deps, identity) {
23742
23958
  const url = new URL(committed);
23743
23959
  derivedFromBoundCrop = cropBound && committed !== beforeCommit && url.hostname === "mmbiz.qpic.cn" && ["http:", "https:"].includes(url.protocol);
23744
23960
  } catch {}
23745
- if (selectedSrc === "" || coverAssetIdentity(committed) !== coverAssetIdentity(selectedSrc) && !derivedFromBoundCrop)
23961
+ if (selectedSrc === "" || coverAssetIdentity(committed) !== coverAssetIdentity(selectedSrc) && !derivedFromBoundCrop && !(selected.soleCandidate === true && selectedSrc.startsWith("data:")))
23746
23962
  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`);
23747
23963
  return null;
23748
23964
  } catch (error) {
23749
23965
  return await warn(`cover: ${error instanceof Error ? error.message : String(error)}`);
23750
23966
  }
23751
23967
  }
23968
+ function genericCoverPathOf(content) {
23969
+ const generic = content.metadata?.coverImage;
23970
+ const genericPath = typeof generic === "string" ? generic : typeof generic?.path === "string" ? generic.path : undefined;
23971
+ return genericPath !== undefined && genericPath.length > 0 ? genericPath : undefined;
23972
+ }
23973
+ function libraryCoverFallback(content) {
23974
+ const meta = content.metadata?.wechatmp;
23975
+ if (meta !== null && typeof meta === "object" && !Array.isArray(meta)) {
23976
+ const coverPath = meta.coverPath;
23977
+ if (typeof coverPath === "string" && coverPath.trim().length > 0)
23978
+ return coverPath.trim();
23979
+ }
23980
+ return genericCoverPathOf(content);
23981
+ }
23752
23982
  function coverSourceOf(content) {
23753
23983
  const meta = content.metadata?.wechatmp;
23754
23984
  if (meta !== null && typeof meta === "object" && !Array.isArray(meta)) {
@@ -23756,9 +23986,7 @@ function coverSourceOf(content) {
23756
23986
  if (declared === "body" || declared === "library")
23757
23987
  return declared;
23758
23988
  }
23759
- const generic = content.metadata?.coverImage;
23760
- const genericPath = typeof generic === "string" ? generic : typeof generic?.path === "string" ? generic.path : undefined;
23761
- return genericPath !== undefined && genericPath.length > 0 ? "body" : "library";
23989
+ return genericCoverPathOf(content) !== undefined ? "body" : "library";
23762
23990
  }
23763
23991
  function audioBlockOf(content) {
23764
23992
  const meta = content.metadata?.wechatmp;
@@ -23776,9 +24004,11 @@ function audioBlockOf(content) {
23776
24004
  async function enrichArticleDraft(page, content, stepTimeoutMs) {
23777
24005
  const enrichMeta = content.metadata?.wechatmp;
23778
24006
  if (enrichMeta === undefined || typeof enrichMeta !== "object" || Array.isArray(enrichMeta))
23779
- return { enrichWarnings: [], coverWarnings: [] };
24007
+ return { enrichWarnings: [], capabilityWarnings: [], coverWarnings: [] };
23780
24008
  const meta = enrichMeta;
23781
- const enrichWarnings = await enrichArticle(page, meta);
24009
+ const detailed = await enrichArticleDetailed(page, meta);
24010
+ const enrichWarnings = [...detailed.warnings];
24011
+ const capabilityWarnings = [...detailed.capabilityWarnings];
23782
24012
  const audio = audioBlockOf(content);
23783
24013
  let audioFailed = false;
23784
24014
  let coverSeeded = false;
@@ -23800,14 +24030,15 @@ async function enrichArticleDraft(page, content, stepTimeoutMs) {
23800
24030
  coverWarnings.push(cover);
23801
24031
  }
23802
24032
  }
23803
- return { enrichWarnings, coverWarnings };
24033
+ return { enrichWarnings, capabilityWarnings, coverWarnings };
23804
24034
  }
23805
24035
  async function composeArticle(input, deps, entry) {
23806
24036
  const page = entry.editor;
23807
24037
  const warnings = [];
24038
+ const figures = await inlineFiguresOf(deps.content);
24039
+ if (figures.length > 0)
24040
+ assertInlineFigureMarkers(bodyOf(deps.content), figures);
23808
24041
  const titlePath = await typeTitle(page, deps);
23809
- await insertBody(page, deps);
23810
- await attachImages(page, input.images, deps);
23811
24042
  for (const warning of [
23812
24043
  await fillOptional(page, DIGEST_INPUT, input.digest ?? "", "\u6458\u8981", deps),
23813
24044
  await fillOptional(page, AUTHOR_INPUT, authorOf(deps.content), "\u4F5C\u8005", deps)
@@ -23815,22 +24046,33 @@ async function composeArticle(input, deps, entry) {
23815
24046
  if (warning !== null)
23816
24047
  warnings.push(warning);
23817
24048
  }
24049
+ if (figures.length > 0) {
24050
+ await attachImages(page, figures.map((figure) => figure.path), deps);
24051
+ const srcs = await waitForInlineFigureSrcs(page, figures.length, deps);
24052
+ const body = bodyOf(deps.content);
24053
+ await insertHtmlBody(page, body, markdownToWechatHtml(withInlineFigureHtml(body, figures, srcs)), deps);
24054
+ await verifyInlineFigureDom(page, BODY_BLOCK, figures, srcs);
24055
+ } else {
24056
+ await insertBody(page, deps);
24057
+ }
24058
+ if (input.images.length > 0)
24059
+ await attachImages(page, input.images, deps);
23818
24060
  await closeOpenDialogs(page);
23819
24061
  const coverSource = coverSourceOf(deps.content);
23820
24062
  const audioRuns = audioBlockOf(deps.content) !== null;
23821
24063
  if (!(coverSource === "library" && audioRuns)) {
23822
24064
  const cover = await setCover(page, coverSource, deps, {
23823
- requested: input.images[0]
24065
+ requested: input.images[0] ?? libraryCoverFallback(deps.content)
23824
24066
  });
23825
24067
  if (cover !== null)
23826
24068
  warnings.push(cover);
23827
24069
  }
23828
- const { enrichWarnings, coverWarnings } = await enrichArticleDraft(page, deps.content, deps.stepTimeoutMs);
24070
+ const { enrichWarnings, capabilityWarnings, coverWarnings } = await enrichArticleDraft(page, deps.content, deps.stepTimeoutMs);
23829
24071
  warnings.push(...coverWarnings);
23830
24072
  const layout = await applyLayout(page, deps);
23831
24073
  if (layout !== null)
23832
24074
  warnings.push(layout);
23833
- return { warnings, titlePath, enrichWarnings };
24075
+ return { warnings, titlePath, enrichWarnings, capabilityWarnings };
23834
24076
  }
23835
24077
  async function composeSticker(input, deps, entry) {
23836
24078
  const page = entry.editor;
@@ -24034,8 +24276,14 @@ function baseMetadata(input, deps, entry) {
24034
24276
  ...cover === undefined ? {} : { coverPath: cover }
24035
24277
  };
24036
24278
  }
24279
+ var INCOMPLETE_DRAFT_MARKER = "\u56FE\u6587\u5185\u5BB9\u4E0D\u5B8C\u6574";
24037
24280
  async function saveDraft(input, deps, entry, composed) {
24038
24281
  const title = titleOf(deps.content);
24282
+ if (input.operation === "\u6587\u7AE0" && bodyOf(deps.content).trim().length > 0) {
24283
+ const bodySelector = await findSelector(entry.editor, BODY_BLOCK, "article body", deps.stepTimeoutMs).catch(() => null);
24284
+ if (bodySelector === null || await bodyLength(entry.editor, bodySelector) === 0)
24285
+ return fail("draft confirmation: article body is empty before \u4FDD\u5B58\u4E3A\u8349\u7A3F \u2014 refusing to save an incomplete draft");
24286
+ }
24039
24287
  let control = null;
24040
24288
  let signal = null;
24041
24289
  let attempts = 0;
@@ -24073,6 +24321,8 @@ async function saveDraft(input, deps, entry, composed) {
24073
24321
  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)})`);
24074
24322
  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)})`);
24075
24323
  }
24324
+ if (signal.includes(INCOMPLETE_DRAFT_MARKER))
24325
+ return fail(`draft confirmation: \u8349\u7A3F\u7BB1 row for '${title}' reported '${signal.replace(/\s+/g, " ").trim()}' \u2014 refusing to certify an incomplete draft`);
24076
24326
  return ResultSchema.parse({
24077
24327
  ok: true,
24078
24328
  target: TARGET,
@@ -24113,12 +24363,11 @@ function savedEditorUrlForMetadata(value) {
24113
24363
  return sanitizeSessionEvidence(value);
24114
24364
  }
24115
24365
  var PUBLIC_DRAFT_SNAPSHOT_SCRIPT = `/* __KK_WECHAT_PUBLISH_SNAPSHOT__ */ (() => {
24116
- const norm = (value) => (value ?? '').replace(/[\\s\\u00a0]+/g, ' ').trim();
24117
24366
  const titleNode = document.querySelector('textarea#title, textarea.js_title');
24118
24367
  const title = titleNode?.value ?? [...document.querySelectorAll('.ProseMirror[data-placeholder*="\u6807\u9898"]')]
24119
24368
  .map((node) => node.textContent ?? '').join(' ');
24120
24369
  const body = [...document.querySelectorAll('.ProseMirror:not([data-placeholder])')]
24121
- .map((node) => norm(node.textContent)).join('\\n');
24370
+ .map((node) => (node.textContent ?? '').replace(/[\\s\\u00a0]+/g, ' ').trim()).join('\\n');
24122
24371
  const media = [
24123
24372
  ...document.querySelectorAll(
24124
24373
  '.ProseMirror mp-common-mpaudio, .ProseMirror mpvoice, .ProseMirror [data-mediaid], .ProseMirror audio, .ProseMirror video, .ProseMirror img',
@@ -24126,7 +24375,7 @@ var PUBLIC_DRAFT_SNAPSHOT_SCRIPT = `/* __KK_WECHAT_PUBLISH_SNAPSHOT__ */ (() =>
24126
24375
  ]
24127
24376
  .map((node) => node.getAttribute('data-mediaid') ?? node.getAttribute('data-id') ??
24128
24377
  node.getAttribute('voice_encode_fileid') ?? node.getAttribute('data-src') ?? node.getAttribute('src') ??
24129
- norm(node.textContent))
24378
+ (node.textContent ?? '').replace(/[\\s\\u00a0]+/g, ' ').trim())
24130
24379
  .map(norm).filter((value) => value.length > 0);
24131
24380
  const area = document.querySelector('#js_cover_area');
24132
24381
  const coverNode = area?.querySelector('.js_cover_preview_new img, img, [style*="background-image"], input[type="hidden"]');
@@ -24615,11 +24864,16 @@ async function runMode(input, deps) {
24615
24864
  if (!result.ok && diagnostics.length > 0) {
24616
24865
  return { ...result, error: `${result.error} \u2014 compose diagnostics: ${diagnostics.join(" | ")}` };
24617
24866
  }
24618
- if (result.ok && composed.enrichWarnings.length > 0 && process.env.WECHATMP_ALLOW_PARTIAL_ENRICH !== "1") {
24867
+ const capabilitySet = new Set(composed.capabilityWarnings ?? []);
24868
+ const blockingEnrichWarnings = composed.enrichWarnings.filter((warning) => !capabilitySet.has(warning));
24869
+ const partialAllowed = process.env.WECHATMP_ALLOW_PARTIAL_ENRICH === "1";
24870
+ const fatalEnrichWarnings = partialAllowed ? blockingEnrichWarnings : composed.enrichWarnings;
24871
+ if (result.ok && fatalEnrichWarnings.length > 0) {
24872
+ const capabilityOnly = blockingEnrichWarnings.length === 0;
24619
24873
  return {
24620
24874
  ...result,
24621
24875
  ok: false,
24622
- error: `draft saved but enrichment did not apply \u2014 ${composed.enrichWarnings.join(" | ")} (set WECHATMP_ALLOW_PARTIAL_ENRICH=1 to accept a partial draft)`
24876
+ error: `draft saved but enrichment did not apply \u2014 ${fatalEnrichWarnings.join(" | ")}${capabilityOnly ? " (set WECHATMP_ALLOW_PARTIAL_ENRICH=1 to accept a partial draft)" : ""}`
24623
24877
  };
24624
24878
  }
24625
24879
  return result;
@@ -24653,7 +24907,7 @@ function markdownToWechatHtml(markdown) {
24653
24907
  for (const line of lines) {
24654
24908
  if (line.startsWith("```")) {
24655
24909
  if (inCode) {
24656
- out.push(`<pre><code>${escapeHtml(code.join(`
24910
+ out.push(`<pre style="overflow-x:auto;max-width:100%;"><code>${escapeHtml(code.join(`
24657
24911
  `))}</code></pre>`);
24658
24912
  code = [];
24659
24913
  inCode = false;
@@ -24708,7 +24962,18 @@ function markdownToWechatHtml(markdown) {
24708
24962
  function escapeHtml(text) {
24709
24963
  return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
24710
24964
  }
24711
- async function insertAudioMaterial(page, input) {
24965
+ async function evalOrFallback(page, script, fallback) {
24966
+ try {
24967
+ return String(await page.evaluate(script) ?? fallback);
24968
+ } catch {
24969
+ return fallback;
24970
+ }
24971
+ }
24972
+ async function insertAudioMaterial(page, input, timing = {}) {
24973
+ const uploadWaitMs = timing.uploadWaitMs ?? 120000;
24974
+ const saveCloseWaitMs = timing.saveCloseWaitMs ?? 30000;
24975
+ const saveDispatchWaitMs = timing.saveDispatchWaitMs ?? 1e4;
24976
+ const postUploadRowRetries = timing.rowRetries ?? 15;
24712
24977
  const { title, audioPath, coverPath } = input;
24713
24978
  let libraryHasCover = false;
24714
24979
  const result = (warning) => ({
@@ -24781,17 +25046,56 @@ async function insertAudioMaterial(page, input) {
24781
25046
  node.getAttribute('data-src') ?? node.getAttribute('src') ?? '';
24782
25047
  return JSON.stringify({ state: 'top', identity });
24783
25048
  })()`;
25049
+ const dumpAudioStall = async (p) => {
25050
+ const path = join6(tmpdir(), `wechatmp-audio-stall-${Date.now()}.png`);
25051
+ try {
25052
+ if (p.screenshot === undefined)
25053
+ return "(no screenshot seam)";
25054
+ await p.screenshot(path);
25055
+ return path;
25056
+ } catch (error) {
25057
+ return `(screenshot failed: ${error instanceof Error ? error.message : String(error)})`;
25058
+ }
25059
+ };
25060
+ 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)); })()`, "");
24784
25061
  const upload = async () => {
25062
+ let sawLiveUpload = false;
25063
+ const failUpload = (warning) => ({ ...result(warning), sawLiveUpload });
25064
+ const uploadDialog = '.weui-desktop-dialog:visible:has(h3.weui-desktop-dialog__title:text-is("\u4E0A\u4F20\u97F3\u9891"))';
25065
+ const isLiveUploadForm = async () => {
25066
+ if (await page.locator(uploadDialog).count() === 0)
25067
+ return false;
25068
+ try {
25069
+ const titleText = await page.locator(`${uploadDialog} h3.weui-desktop-dialog__title`).first().textContent?.() ?? "";
25070
+ return titleText.trim() === "\u4E0A\u4F20\u97F3\u9891";
25071
+ } catch {
25072
+ return false;
25073
+ }
25074
+ };
24785
25075
  const uploadControl = await trySelectors(page, UPLOAD_AUDIO);
24786
25076
  if (!uploadControl.found)
24787
- return result("\u97F3\u9891: \u4E0A\u4F20\u97F3\u9891 control not found in the audio dialog");
25077
+ return failUpload("\u97F3\u9891: \u4E0A\u4F20\u97F3\u9891 control not found in the audio dialog");
24788
25078
  await clickSelector(page, uploadControl.selector ?? UPLOAD_AUDIO[0] ?? "text=\u4E0A\u4F20\u97F3\u9891", 8000);
24789
25079
  const audioInput = await trySelectors(page, AUDIO_UPLOAD_INPUT, { visible: false });
24790
25080
  if (!audioInput.found)
24791
- return result("\u97F3\u9891: no audio file input appeared");
25081
+ return failUpload("\u97F3\u9891: no audio file input appeared");
24792
25082
  await uploadFile(asPlaywrightPage(page), audioInput.selector ?? AUDIO_UPLOAD_INPUT.join(", "), audioPath, {
24793
- timeoutMs: 60000
25083
+ timeoutMs: 120000
24794
25084
  });
25085
+ sawLiveUpload = await isLiveUploadForm();
25086
+ if (sawLiveUpload) {
25087
+ const audioName = baseName(audioPath).replace(/\.[^.]+$/, "");
25088
+ 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");
25089
+ const transientUpload = async () => {
25090
+ if (await page.locator(`${uploadDialog} button:has-text("\u91CD\u65B0\u4E0A\u4F20")`).count() === 0)
25091
+ return false;
25092
+ 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 ?? '') : ''; })()`, "");
25093
+ return /100%/.test(text);
25094
+ };
25095
+ const uploaded = await waitUntil(async () => await settledUpload() || await transientUpload(), uploadWaitMs);
25096
+ if (!uploaded)
25097
+ 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)}`);
25098
+ }
24795
25099
  const coverControl = await trySelectors(page, UPLOAD_COVER);
24796
25100
  if (coverControl.found) {
24797
25101
  await clickSelector(page, coverControl.selector ?? UPLOAD_COVER[0] ?? "text=\u4E0A\u4F20\u5C01\u9762", 8000);
@@ -24804,10 +25108,10 @@ async function insertAudioMaterial(page, input) {
24804
25108
  if (hasChooser) {
24805
25109
  const libraryReady = await waitUntil(async () => Boolean(await page.evaluate(`!document.querySelector('#js_image_dialog_list_wrp .weui-desktop-loading')`)), 5000);
24806
25110
  if (!libraryReady)
24807
- return result("\u97F3\u9891: \u5C01\u9762\u7D20\u6750\u5E93\u52A0\u8F7D\u672A\u5B8C\u6210\uFF0C\u672A\u4E0A\u4F20\u91CD\u590D\u5C01\u9762");
25111
+ return failUpload("\u97F3\u9891: \u5C01\u9762\u7D20\u6750\u5E93\u52A0\u8F7D\u672A\u5B8C\u6210\uFF0C\u672A\u4E0A\u4F20\u91CD\u590D\u5C01\u9762");
24808
25112
  existing = Number(await page.evaluate(`([...document.querySelectorAll('.weui-desktop-img-picker__item')].filter(row => row.offsetWidth > 0 && row.querySelector('.weui-desktop-img-picker__img-title')?.textContent?.trim() === ${JSON.stringify(coverName)})).length`));
24809
25113
  if (existing > 1)
24810
- return result("\u97F3\u9891: \u5185\u5BB9\u7ED1\u5B9A\u5C01\u9762\u5B58\u5728\u591A\u4E2A\u540C\u540D\u7D20\u6750\uFF0C\u672A\u731C\u6D4B\u9009\u62E9");
25114
+ return failUpload("\u97F3\u9891: \u5185\u5BB9\u7ED1\u5B9A\u5C01\u9762\u5B58\u5728\u591A\u4E2A\u540C\u540D\u7D20\u6750\uFF0C\u672A\u731C\u6D4B\u9009\u62E9");
24811
25115
  }
24812
25116
  let uploadPath = coverPath;
24813
25117
  let temporaryDir;
@@ -24836,10 +25140,13 @@ async function insertAudioMaterial(page, input) {
24836
25140
  return row.classList.contains('selected');
24837
25141
  })()`)), 30000);
24838
25142
  if (!selected)
24839
- return result("\u97F3\u9891: \u4E0A\u4F20\u5C01\u9762\u672A\u51FA\u73B0\u552F\u4E00\u5DF2\u9009\u4E2D\u7684\u540C\u540D\u56FE\u7247\uFF0C\u672A\u63D0\u4EA4\u5C01\u9762");
25143
+ return failUpload("\u97F3\u9891: \u4E0A\u4F20\u5C01\u9762\u672A\u51FA\u73B0\u552F\u4E00\u5DF2\u9009\u4E2D\u7684\u540C\u540D\u56FE\u7247\uFF0C\u672A\u63D0\u4EA4\u5C01\u9762");
24840
25144
  libraryHasCover = true;
24841
25145
  const next = await findSelector(page, [`${chooser} button:has-text("\u4E0B\u4E00\u6B65"):not(.weui-desktop-btn_disabled)`], "\u97F3\u9891\u5C01\u9762 \u4E0B\u4E00\u6B65", 30000);
24842
25146
  await clickSelector(page, next, 8000);
25147
+ if (sawLiveUpload && await page.locator(`${chooser} button:has-text("\u4E0A\u4E00\u6B65")`).count() > 0) {
25148
+ await page.waitForTimeout?.(2000);
25149
+ }
24843
25150
  const finish = await findSelector(page, [`${chooser} button:has-text("\u5B8C\u6210"):not(.weui-desktop-btn_disabled)`], "\u97F3\u9891\u5C01\u9762 \u5B8C\u6210", 30000);
24844
25151
  await clickSelector(page, finish, 8000);
24845
25152
  let closed = await waitUntil(async () => !await page.locator(chooser).first().isVisible(), 25000);
@@ -24863,7 +25170,7 @@ async function insertAudioMaterial(page, input) {
24863
25170
  }
24864
25171
  if (!closed) {
24865
25172
  const inventory = await openDialogInventory(page);
24866
- return result(`\u97F3\u9891: \u5C01\u9762\u9009\u62E9\u5668\u5B8C\u6210\u540E\u672A\u5173\u95ED\uFF0C\u672A\u4FDD\u5B58\u97F3\u9891${inventory ? ` (dialogs: ${inventory})` : ""}`);
25173
+ return failUpload(`\u97F3\u9891: \u5C01\u9762\u9009\u62E9\u5668\u5B8C\u6210\u540E\u672A\u5173\u95ED\uFF0C\u672A\u4FDD\u5B58\u97F3\u9891${inventory ? ` (dialogs: ${inventory})` : ""}`);
24867
25174
  }
24868
25175
  }
24869
25176
  } finally {
@@ -24879,10 +25186,29 @@ async function insertAudioMaterial(page, input) {
24879
25186
  await fillSelector(page, titleInput.selector ?? AUDIO_TITLE_INPUT.join(", "), title);
24880
25187
  const agreed = String(await page.evaluate(AGREE));
24881
25188
  if (agreed !== "checked")
24882
- return result(`\u97F3\u9891: \u670D\u52A1\u89C4\u5219\u52FE\u9009\u5931\u8D25 (${agreed})`);
25189
+ return failUpload(`\u97F3\u9891: \u670D\u52A1\u89C4\u5219\u52FE\u9009\u5931\u8D25 (${agreed})`);
24883
25190
  const save = await findSelector(page, UPLOAD_SAVE.map((selector) => `${selector}:not(.weui-desktop-btn_disabled):not([disabled])`), "\u97F3\u9891\u4E0A\u4F20\u5B8C\u6210\u4E14\u5C01\u9762\u5DF2\u63D0\u4EA4\u540E\u7684\u4FDD\u5B58\u6309\u94AE", 90000);
25191
+ if (sawLiveUpload) {
25192
+ await evalOrFallback(page, '(() => { window.__kkToasts = []; new MutationObserver(() => { const t = document.querySelector(".weui-desktop-toast"); if (t && t.textContent) window.__kkToasts.push(t.textContent.trim().slice(0, 200)); }).observe(document.body, { subtree: true, childList: true, characterData: true }); })()', "");
25193
+ }
24884
25194
  await clickSelector(page, save, 8000);
24885
- return result("");
25195
+ if (sawLiveUpload) {
25196
+ let formClosed = await waitUntil(async () => !await isLiveUploadForm(), saveCloseWaitMs);
25197
+ if (!formClosed) {
25198
+ const dispatched = await evalOrFallback(page, '(() => { const form = [...document.querySelectorAll(".weui-desktop-dialog")].find((d) => d.querySelector(".title_form_wrp")); const btn = form && [...form.querySelectorAll("button")].find((b) => (b.textContent ?? "").trim() === "\u4FDD\u5B58"); if (!btn) return "no-btn"; btn.click(); return btn.disabled ? "was-disabled" : "clicked"; })()', "null");
25199
+ formClosed = await waitUntil(async () => !await isLiveUploadForm(), saveDispatchWaitMs);
25200
+ if (!formClosed) {
25201
+ const saveDiagnostics = `(() => {
25202
+ const form = [...document.querySelectorAll(".weui-desktop-dialog")].find((d) => d.querySelector(".title_form_wrp"));
25203
+ const btn = form && [...form.querySelectorAll("button")].find((b) => (b.textContent ?? "").trim() === "\u4FDD\u5B58");
25204
+ return JSON.stringify({ btn: btn ? { disabled: btn.disabled, offW: btn.offsetWidth } : null, toasts: (window.__kkToasts ?? []).slice(-3) });
25205
+ })()`;
25206
+ const diag = (await evalOrFallback(page, saveDiagnostics, "")).slice(0, 400);
25207
+ return failUpload(`\u97F3\u9891: \u4FDD\u5B58\u5931\u8D25\uFF0C\u4E0A\u4F20\u5F39\u7A97\u672A\u5173\u95ED\uFF08dispatch=${dispatched} ${diag}\uFF09`);
25208
+ }
25209
+ }
25210
+ }
25211
+ return failUpload("");
24886
25212
  };
24887
25213
  const matchOnce = async () => {
24888
25214
  try {
@@ -24891,9 +25217,9 @@ async function insertAudioMaterial(page, input) {
24891
25217
  return "error";
24892
25218
  }
24893
25219
  };
24894
- const awaitMatch = async () => {
25220
+ const awaitMatch = async (retries = AUDIO_ROW_RETRIES) => {
24895
25221
  let match = await matchOnce();
24896
- for (let i = 0;match === "missing" && i < AUDIO_ROW_RETRIES; i += 1) {
25222
+ for (let i = 0;match === "missing" && i < retries; i += 1) {
24897
25223
  await page.waitForTimeout?.(AUDIO_ROW_SETTLE_MS);
24898
25224
  match = await matchOnce();
24899
25225
  }
@@ -24907,14 +25233,17 @@ async function insertAudioMaterial(page, input) {
24907
25233
  await page.evaluate(`document.querySelector(${JSON.stringify(AUDIO_MENU)})?.click()`);
24908
25234
  await waitForVisible(page, AUDIO_DIALOG, AUDIO_DIALOG_TIMEOUT_MS);
24909
25235
  let match = await awaitMatch();
25236
+ let postSavePoll = false;
24910
25237
  if (match === "missing") {
24911
25238
  const uploadResult = await upload();
25239
+ postSavePoll = uploadResult.sawLiveUpload;
24912
25240
  if (uploadResult.warning !== "") {
24913
- await page.evaluate(CANCEL);
25241
+ if (!uploadResult.sawLiveUpload)
25242
+ await page.evaluate(CANCEL);
24914
25243
  return result(uploadResult.warning);
24915
25244
  }
24916
25245
  await waitForVisible(page, AUDIO_DIALOG, AUDIO_DIALOG_TIMEOUT_MS);
24917
- match = await awaitMatch();
25246
+ match = await awaitMatch(postSavePoll ? postUploadRowRetries : AUDIO_ROW_RETRIES);
24918
25247
  if (match === "missing") {
24919
25248
  await page.evaluate(CANCEL);
24920
25249
  return result(`\u97F3\u9891: \u4FDD\u5B58\u540E\u7D20\u6750\u5217\u8868\u672A\u51FA\u73B0\u300C${title}\u300D\uFF0C\u672A\u63D2\u5165\u97F3\u9891`);
@@ -24939,7 +25268,14 @@ async function insertAudioMaterial(page, input) {
24939
25268
  await page.evaluate(CANCEL);
24940
25269
  return result("\u97F3\u9891: \u7D20\u6750\u5339\u914D\u63A2\u6D4B\u8FD4\u56DE\u672A\u77E5\u7ED3\u679C\uFF0C\u672A\u63D2\u5165\u97F3\u9891");
24941
25270
  }
24942
- if (await page.evaluate(INSERT) !== true) {
25271
+ let inserted = await page.evaluate(INSERT) === true;
25272
+ if (!inserted && postSavePoll) {
25273
+ for (let i = 0;!inserted && i < 5; i += 1) {
25274
+ await page.waitForTimeout?.(500);
25275
+ inserted = await page.evaluate(INSERT) === true;
25276
+ }
25277
+ }
25278
+ if (!inserted) {
24943
25279
  await page.evaluate(CANCEL);
24944
25280
  return result("\u97F3\u9891: \u63D2\u5165\u6309\u94AE\u672A\u627E\u5230\uFF0C\u8BF7\u624B\u52A8\u63D2\u5165");
24945
25281
  }
@@ -25103,7 +25439,7 @@ var wechatSessionConfig = {
25103
25439
  }
25104
25440
  };
25105
25441
  async function defaultOpenConsole(profileDir) {
25106
- const { page, context } = await openWithState(profileDir, true);
25442
+ const { page, context } = await openWithState(profileDir, process.env.WECHATMP_HEADLESS !== "false");
25107
25443
  return {
25108
25444
  ...wrapPlaywrightContext(context, page),
25109
25445
  persistSession: () => persistWechatSessionState(context, profileDir)