@dinoxx/dinox-cli 2.18.5 → 2.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (592) hide show
  1. package/LICENSE +15 -0
  2. package/README.md +17 -17
  3. package/dist/chunks/applePodcast-V4FSJOC5.js +169 -0
  4. package/dist/chunks/bbc-NTMRPYRF.js +570 -0
  5. package/dist/chunks/bilibili-UA3MBSPH.js +835 -0
  6. package/dist/chunks/bohaishibei-B7UVXH4Y.js +246 -0
  7. package/dist/chunks/chunk-224ML7QC.js +21 -0
  8. package/dist/chunks/chunk-2LW76QIL.js +32 -0
  9. package/dist/chunks/chunk-2M7RJATW.js +60 -0
  10. package/dist/chunks/chunk-3EKNTO6G.js +61 -0
  11. package/dist/chunks/chunk-3VZNZWDG.js +437 -0
  12. package/dist/chunks/chunk-5JF7J5MP.js +114 -0
  13. package/dist/chunks/chunk-5KU25TMX.js +26 -0
  14. package/dist/chunks/chunk-67RXND3H.js +65 -0
  15. package/dist/chunks/chunk-6AZT4ARG.js +1491 -0
  16. package/dist/chunks/chunk-6D3QLMRM.js +421 -0
  17. package/dist/chunks/chunk-6VMHHE5Y.js +235 -0
  18. package/dist/chunks/chunk-77UP745T.js +143 -0
  19. package/dist/chunks/chunk-7A5QISPG.js +19 -0
  20. package/dist/chunks/chunk-7ODU7LXP.js +31 -0
  21. package/dist/chunks/chunk-A6WF7CZL.js +904 -0
  22. package/dist/chunks/chunk-ABYPGMDC.js +100 -0
  23. package/dist/chunks/chunk-AHRCI2RW.js +141 -0
  24. package/dist/chunks/chunk-BDLS5EEP.js +49 -0
  25. package/dist/chunks/chunk-BKCNERPB.js +246 -0
  26. package/dist/chunks/chunk-BZQYECIH.js +54 -0
  27. package/dist/chunks/chunk-D5SBKLDX.js +71 -0
  28. package/dist/chunks/chunk-DR6BGSZM.js +865 -0
  29. package/dist/chunks/chunk-F7BDWXBG.js +57 -0
  30. package/dist/chunks/chunk-FGQRYB7F.js +34 -0
  31. package/dist/chunks/chunk-FIQYJ6KZ.js +19 -0
  32. package/dist/chunks/chunk-FKLZZGEX.js +116 -0
  33. package/dist/chunks/chunk-FZGEWY5L.js +37 -0
  34. package/dist/chunks/chunk-GTDX2LIJ.js +265 -0
  35. package/dist/chunks/chunk-HIJXC3RT.js +194 -0
  36. package/dist/chunks/chunk-HQJUJYUM.js +36 -0
  37. package/dist/chunks/chunk-IAEJG5NI.js +50 -0
  38. package/dist/chunks/chunk-KCHHY6QB.js +65 -0
  39. package/dist/chunks/chunk-KL75BFYJ.js +71 -0
  40. package/dist/chunks/chunk-KOAKG2QU.js +45 -0
  41. package/dist/chunks/chunk-MCFXD2LS.js +66 -0
  42. package/dist/chunks/chunk-MLOITAK6.js +29 -0
  43. package/dist/chunks/chunk-N44NRKDJ.js +101 -0
  44. package/dist/chunks/chunk-N6ALWINB.js +14115 -0
  45. package/dist/chunks/chunk-NGIIELO4.js +61 -0
  46. package/dist/chunks/chunk-OG6MBAGC.js +95 -0
  47. package/dist/chunks/chunk-P4LG4DIO.js +108 -0
  48. package/dist/chunks/chunk-PJDD4R46.js +77 -0
  49. package/dist/chunks/chunk-PK5AOVLU.js +107 -0
  50. package/dist/chunks/chunk-PTFGE4KS.js +66 -0
  51. package/dist/chunks/chunk-Q6G7VO5G.js +67 -0
  52. package/dist/chunks/chunk-QFUD3I7W.js +185 -0
  53. package/dist/chunks/chunk-QNIYFLJT.js +39 -0
  54. package/dist/chunks/chunk-QZQRG3JY.js +86 -0
  55. package/dist/chunks/chunk-RKJYKUQD.js +91 -0
  56. package/dist/chunks/chunk-TAENC45D.js +160 -0
  57. package/dist/chunks/chunk-TILRKKRN.js +20481 -0
  58. package/dist/chunks/chunk-TIXOORAP.js +60 -0
  59. package/dist/chunks/chunk-ULKGDBAJ.js +80 -0
  60. package/dist/chunks/chunk-URYABAYN.js +72 -0
  61. package/dist/chunks/chunk-VNB4ZFLN.js +86 -0
  62. package/dist/chunks/chunk-W7R5JTSA.js +42 -0
  63. package/dist/chunks/chunk-WC3GSQBC.js +25699 -0
  64. package/dist/chunks/chunk-WMJXAF3X.js +55 -0
  65. package/dist/chunks/chunk-X36EIV25.js +93 -0
  66. package/dist/chunks/chunk-X7IZXCSL.js +60 -0
  67. package/dist/chunks/chunk-XEPDFQYD.js +215 -0
  68. package/dist/chunks/chunk-XFVLNCOW.js +171 -0
  69. package/dist/chunks/chunk-XMMTGPZ6.js +1332 -0
  70. package/dist/chunks/chunk-XQZUX7OT.js +39 -0
  71. package/dist/chunks/chunk-XZLFMJOG.js +72 -0
  72. package/dist/chunks/chunk-ZGF3OEWR.js +84 -0
  73. package/dist/chunks/chunk-ZHKS4R4P.js +1215 -0
  74. package/dist/chunks/cookies-6QQHSM26.js +34 -0
  75. package/dist/chunks/dedaoNote-KJ32ZQLS.js +418 -0
  76. package/dist/chunks/doubanGroup-HR4K2KMY.js +429 -0
  77. package/dist/chunks/doubao-MXUHPLUB.js +462 -0
  78. package/dist/chunks/douyin-UU2FSQPS.js +566 -0
  79. package/dist/chunks/ensure-MLNCD2SD.js +18 -0
  80. package/dist/chunks/execute-57M65KKK.js +17 -0
  81. package/dist/chunks/facebook-SZFOVE7R.js +878 -0
  82. package/dist/chunks/feishu-ISWRJ7HI.js +877 -0
  83. package/dist/chunks/ima-D7CX5WR4.js +202 -0
  84. package/dist/chunks/instagram-HNDPO37H.js +939 -0
  85. package/dist/chunks/install-IIMVFNAT.js +303 -0
  86. package/dist/chunks/jike-H7L4LJTN.js +445 -0
  87. package/dist/chunks/mcp-PZBHAYXQ.js +297 -0
  88. package/dist/chunks/mcpServer-T4DNYR7R.js +436 -0
  89. package/dist/chunks/metaso-ZVZW5UBB.js +194 -0
  90. package/dist/chunks/run-GCMWLTIV.js +1464 -0
  91. package/dist/chunks/runCli-SBQE2VQJ.js +464 -0
  92. package/dist/chunks/setup-EEU6GSWX.js +378 -0
  93. package/dist/chunks/threads-ADW6IANQ.js +657 -0
  94. package/dist/chunks/twitter-NAGCB3NI.js +1148 -0
  95. package/dist/chunks/web-QFKZCM4F.js +31 -0
  96. package/dist/chunks/wechat-OXNNLT4J.js +1551 -0
  97. package/dist/chunks/weibo-PMVGDNQU.js +641 -0
  98. package/dist/chunks/workbuddy-NNAXIIIZ.js +426 -0
  99. package/dist/chunks/xiaoheihe-WFQJRBAD.js +316 -0
  100. package/dist/chunks/xiaohongshu-5CXBELGW.js +1833 -0
  101. package/dist/chunks/xiaoyuzhou-6L6IB46Y.js +322 -0
  102. package/dist/chunks/youtube-52NGBTQC.js +58 -0
  103. package/dist/chunks/zcool-HDSWK4KD.js +755 -0
  104. package/dist/chunks/zhihu-EX2VRJYY.js +1024 -0
  105. package/dist/dinox.js +137 -51
  106. package/dist/dsh-plugin/lib/client.js +754 -317
  107. package/dist/dsh-plugin/lib/index.js +7 -2
  108. package/dist/dsh-plugin/package.json +1 -1
  109. package/dist/dsh-plugin/runtime.json +3 -3
  110. package/dist/editor-ui/mcp-app.html +325 -303
  111. package/package.json +81 -63
  112. package/dist/ai/ragxClient.d.ts +0 -15
  113. package/dist/ai/ragxClient.js +0 -71
  114. package/dist/auth/devicePair.d.ts +0 -62
  115. package/dist/auth/devicePair.js +0 -377
  116. package/dist/auth/userInfo.d.ts +0 -26
  117. package/dist/auth/userInfo.js +0 -224
  118. package/dist/cli.d.ts +0 -2
  119. package/dist/cli.js +0 -130
  120. package/dist/cliTypes.d.ts +0 -7
  121. package/dist/cliTypes.js +0 -1
  122. package/dist/commands/auth/index.d.ts +0 -34
  123. package/dist/commands/auth/index.js +0 -605
  124. package/dist/commands/batch.d.ts +0 -35
  125. package/dist/commands/batch.js +0 -202
  126. package/dist/commands/boxes/index.d.ts +0 -4
  127. package/dist/commands/boxes/index.js +0 -382
  128. package/dist/commands/boxes/model.d.ts +0 -37
  129. package/dist/commands/boxes/model.js +0 -93
  130. package/dist/commands/boxes/operations.d.ts +0 -86
  131. package/dist/commands/boxes/operations.js +0 -448
  132. package/dist/commands/boxes/repo.d.ts +0 -36
  133. package/dist/commands/boxes/repo.js +0 -320
  134. package/dist/commands/boxes/store.d.ts +0 -22
  135. package/dist/commands/boxes/store.js +0 -143
  136. package/dist/commands/config/index.d.ts +0 -5
  137. package/dist/commands/config/index.js +0 -105
  138. package/dist/commands/descriptor/register.d.ts +0 -8
  139. package/dist/commands/descriptor/register.js +0 -122
  140. package/dist/commands/descriptor/types.d.ts +0 -37
  141. package/dist/commands/descriptor/types.js +0 -17
  142. package/dist/commands/doctor.d.ts +0 -126
  143. package/dist/commands/doctor.js +0 -558
  144. package/dist/commands/domain/options.d.ts +0 -10
  145. package/dist/commands/domain/options.js +0 -75
  146. package/dist/commands/domain/run.d.ts +0 -24
  147. package/dist/commands/domain/run.js +0 -137
  148. package/dist/commands/editor/index.d.ts +0 -4
  149. package/dist/commands/editor/index.js +0 -155
  150. package/dist/commands/gateway/index.d.ts +0 -4
  151. package/dist/commands/gateway/index.js +0 -340
  152. package/dist/commands/graph/index.d.ts +0 -4
  153. package/dist/commands/graph/index.js +0 -173
  154. package/dist/commands/graph/repo.d.ts +0 -40
  155. package/dist/commands/graph/repo.js +0 -201
  156. package/dist/commands/info/index.d.ts +0 -4
  157. package/dist/commands/info/index.js +0 -75
  158. package/dist/commands/mcp.d.ts +0 -6
  159. package/dist/commands/mcp.js +0 -47
  160. package/dist/commands/meta/index.d.ts +0 -4
  161. package/dist/commands/meta/index.js +0 -60
  162. package/dist/commands/meta/repo.d.ts +0 -30
  163. package/dist/commands/meta/repo.js +0 -76
  164. package/dist/commands/notes/actions.d.ts +0 -12
  165. package/dist/commands/notes/actions.js +0 -591
  166. package/dist/commands/notes/bulk.d.ts +0 -35
  167. package/dist/commands/notes/bulk.js +0 -195
  168. package/dist/commands/notes/contentEngine.d.ts +0 -95
  169. package/dist/commands/notes/contentEngine.js +0 -710
  170. package/dist/commands/notes/contentPatch.d.ts +0 -114
  171. package/dist/commands/notes/contentPatch.js +0 -450
  172. package/dist/commands/notes/contentPatchCommand.d.ts +0 -6
  173. package/dist/commands/notes/contentPatchCommand.js +0 -164
  174. package/dist/commands/notes/createFromTemplate.d.ts +0 -35
  175. package/dist/commands/notes/createFromTemplate.js +0 -58
  176. package/dist/commands/notes/descriptors.d.ts +0 -4
  177. package/dist/commands/notes/descriptors.js +0 -548
  178. package/dist/commands/notes/detailContent.d.ts +0 -19
  179. package/dist/commands/notes/detailContent.js +0 -62
  180. package/dist/commands/notes/dryRun.d.ts +0 -33
  181. package/dist/commands/notes/dryRun.js +0 -133
  182. package/dist/commands/notes/export.d.ts +0 -27
  183. package/dist/commands/notes/export.js +0 -252
  184. package/dist/commands/notes/index.d.ts +0 -2
  185. package/dist/commands/notes/index.js +0 -2
  186. package/dist/commands/notes/metadataMutation.d.ts +0 -29
  187. package/dist/commands/notes/metadataMutation.js +0 -138
  188. package/dist/commands/notes/repo/read.d.ts +0 -8
  189. package/dist/commands/notes/repo/read.js +0 -302
  190. package/dist/commands/notes/repo/resolve.d.ts +0 -8
  191. package/dist/commands/notes/repo/resolve.js +0 -187
  192. package/dist/commands/notes/repo/search.d.ts +0 -43
  193. package/dist/commands/notes/repo/search.js +0 -513
  194. package/dist/commands/notes/repo/semantic.d.ts +0 -14
  195. package/dist/commands/notes/repo/semantic.js +0 -31
  196. package/dist/commands/notes/repo/shared.d.ts +0 -192
  197. package/dist/commands/notes/repo/shared.js +0 -102
  198. package/dist/commands/notes/repo/write.d.ts +0 -27
  199. package/dist/commands/notes/repo/write.js +0 -262
  200. package/dist/commands/notes/repo.d.ts +0 -7
  201. package/dist/commands/notes/repo.js +0 -7
  202. package/dist/commands/notes/runtime.d.ts +0 -20
  203. package/dist/commands/notes/runtime.js +0 -175
  204. package/dist/commands/notes/searchOutput.d.ts +0 -15
  205. package/dist/commands/notes/searchOutput.js +0 -54
  206. package/dist/commands/notes/searchResponse.d.ts +0 -54
  207. package/dist/commands/notes/searchResponse.js +0 -57
  208. package/dist/commands/notes/searchSql.d.ts +0 -11
  209. package/dist/commands/notes/searchSql.js +0 -614
  210. package/dist/commands/notes/searchTime.d.ts +0 -9
  211. package/dist/commands/notes/searchTime.js +0 -85
  212. package/dist/commands/notes/semantic.d.ts +0 -116
  213. package/dist/commands/notes/semantic.js +0 -332
  214. package/dist/commands/notes/writeReceipt.d.ts +0 -20
  215. package/dist/commands/notes/writeReceipt.js +0 -82
  216. package/dist/commands/prompt/index.d.ts +0 -5
  217. package/dist/commands/prompt/index.js +0 -132
  218. package/dist/commands/prompt/repo.d.ts +0 -28
  219. package/dist/commands/prompt/repo.js +0 -220
  220. package/dist/commands/properties/index.d.ts +0 -16
  221. package/dist/commands/properties/index.js +0 -640
  222. package/dist/commands/properties/repo.d.ts +0 -150
  223. package/dist/commands/properties/repo.js +0 -272
  224. package/dist/commands/runtime.d.ts +0 -54
  225. package/dist/commands/runtime.js +0 -228
  226. package/dist/commands/savedViews/fields.d.ts +0 -28
  227. package/dist/commands/savedViews/fields.js +0 -87
  228. package/dist/commands/savedViews/index.d.ts +0 -7
  229. package/dist/commands/savedViews/index.js +0 -506
  230. package/dist/commands/savedViews/model.d.ts +0 -45
  231. package/dist/commands/savedViews/model.js +0 -90
  232. package/dist/commands/savedViews/repo.d.ts +0 -125
  233. package/dist/commands/savedViews/repo.js +0 -393
  234. package/dist/commands/schema/commandMetadata.d.ts +0 -2
  235. package/dist/commands/schema/commandMetadata.js +0 -18
  236. package/dist/commands/schema/globalOptions.d.ts +0 -11
  237. package/dist/commands/schema/globalOptions.js +0 -11
  238. package/dist/commands/schema/index.d.ts +0 -5
  239. package/dist/commands/schema/index.js +0 -130
  240. package/dist/commands/schema/renderSkills.d.ts +0 -12
  241. package/dist/commands/schema/renderSkills.js +0 -364
  242. package/dist/commands/schema/spec.d.ts +0 -5
  243. package/dist/commands/schema/spec.js +0 -74
  244. package/dist/commands/schema/types.d.ts +0 -34
  245. package/dist/commands/schema/types.js +0 -1
  246. package/dist/commands/skills/index.d.ts +0 -80
  247. package/dist/commands/skills/index.js +0 -572
  248. package/dist/commands/storage/index.d.ts +0 -4
  249. package/dist/commands/storage/index.js +0 -270
  250. package/dist/commands/storage/repo/configs.d.ts +0 -30
  251. package/dist/commands/storage/repo/configs.js +0 -259
  252. package/dist/commands/storage/repo/operations.d.ts +0 -25
  253. package/dist/commands/storage/repo/operations.js +0 -339
  254. package/dist/commands/storage/repo/remote.d.ts +0 -32
  255. package/dist/commands/storage/repo/remote.js +0 -132
  256. package/dist/commands/storage/repo/resources.d.ts +0 -12
  257. package/dist/commands/storage/repo/resources.js +0 -134
  258. package/dist/commands/storage/repo/shared.d.ts +0 -181
  259. package/dist/commands/storage/repo/shared.js +0 -36
  260. package/dist/commands/storage/repo/targets.d.ts +0 -12
  261. package/dist/commands/storage/repo/targets.js +0 -178
  262. package/dist/commands/storage/repo.d.ts +0 -3
  263. package/dist/commands/storage/repo.js +0 -4
  264. package/dist/commands/sync.d.ts +0 -27
  265. package/dist/commands/sync.js +0 -153
  266. package/dist/commands/tags/content.d.ts +0 -32
  267. package/dist/commands/tags/content.js +0 -252
  268. package/dist/commands/tags/index.d.ts +0 -4
  269. package/dist/commands/tags/index.js +0 -404
  270. package/dist/commands/tags/model.d.ts +0 -38
  271. package/dist/commands/tags/model.js +0 -100
  272. package/dist/commands/tags/operations.d.ts +0 -105
  273. package/dist/commands/tags/operations.js +0 -468
  274. package/dist/commands/tags/repo.d.ts +0 -27
  275. package/dist/commands/tags/repo.js +0 -236
  276. package/dist/commands/tags/store.d.ts +0 -28
  277. package/dist/commands/tags/store.js +0 -166
  278. package/dist/commands/templates/index.d.ts +0 -4
  279. package/dist/commands/templates/index.js +0 -290
  280. package/dist/commands/templates/model.d.ts +0 -28
  281. package/dist/commands/templates/model.js +0 -195
  282. package/dist/commands/templates/repo.d.ts +0 -53
  283. package/dist/commands/templates/repo.js +0 -78
  284. package/dist/commands/todo/contentModel.d.ts +0 -31
  285. package/dist/commands/todo/contentModel.js +0 -375
  286. package/dist/commands/todo/dryRun.d.ts +0 -24
  287. package/dist/commands/todo/dryRun.js +0 -137
  288. package/dist/commands/todo/index.d.ts +0 -10
  289. package/dist/commands/todo/index.js +0 -445
  290. package/dist/commands/todo/repo.d.ts +0 -136
  291. package/dist/commands/todo/repo.js +0 -428
  292. package/dist/commands/todo/taskIdentity.d.ts +0 -2
  293. package/dist/commands/todo/taskIdentity.js +0 -64
  294. package/dist/commands/todo/taskModel.d.ts +0 -37
  295. package/dist/commands/todo/taskModel.js +0 -359
  296. package/dist/commands/update.d.ts +0 -46
  297. package/dist/commands/update.js +0 -326
  298. package/dist/commands/writeConfirmation.d.ts +0 -13
  299. package/dist/commands/writeConfirmation.js +0 -54
  300. package/dist/commands/writeDryRun.d.ts +0 -88
  301. package/dist/commands/writeDryRun.js +0 -162
  302. package/dist/commands/writeDurability.d.ts +0 -5
  303. package/dist/commands/writeDurability.js +0 -22
  304. package/dist/commands/writeReceipt.d.ts +0 -13
  305. package/dist/commands/writeReceipt.js +0 -12
  306. package/dist/config/keys.d.ts +0 -9
  307. package/dist/config/keys.js +0 -14
  308. package/dist/config/paths.d.ts +0 -6
  309. package/dist/config/paths.js +0 -55
  310. package/dist/config/resolve.d.ts +0 -4
  311. package/dist/config/resolve.js +0 -68
  312. package/dist/config/serviceEndpoints.d.ts +0 -5
  313. package/dist/config/serviceEndpoints.js +0 -5
  314. package/dist/config/store.d.ts +0 -8
  315. package/dist/config/store.js +0 -149
  316. package/dist/config/types.d.ts +0 -55
  317. package/dist/config/types.js +0 -1
  318. package/dist/constants/links.d.ts +0 -18
  319. package/dist/constants/links.js +0 -26
  320. package/dist/contract/snapshot.d.ts +0 -30
  321. package/dist/contract/snapshot.js +0 -114
  322. package/dist/daemon/autoInstall.d.ts +0 -32
  323. package/dist/daemon/autoInstall.js +0 -106
  324. package/dist/daemon/client.d.ts +0 -29
  325. package/dist/daemon/client.js +0 -418
  326. package/dist/daemon/connectivity.d.ts +0 -20
  327. package/dist/daemon/connectivity.js +0 -42
  328. package/dist/daemon/ensure.d.ts +0 -1
  329. package/dist/daemon/ensure.js +0 -120
  330. package/dist/daemon/env.d.ts +0 -8
  331. package/dist/daemon/env.js +0 -81
  332. package/dist/daemon/forward.d.ts +0 -37
  333. package/dist/daemon/forward.js +0 -155
  334. package/dist/daemon/fresh.d.ts +0 -4
  335. package/dist/daemon/fresh.js +0 -10
  336. package/dist/daemon/index.d.ts +0 -80
  337. package/dist/daemon/index.js +0 -727
  338. package/dist/daemon/launch.d.ts +0 -43
  339. package/dist/daemon/launch.js +0 -124
  340. package/dist/daemon/lifecycle.d.ts +0 -51
  341. package/dist/daemon/lifecycle.js +0 -182
  342. package/dist/daemon/log.d.ts +0 -14
  343. package/dist/daemon/log.js +0 -57
  344. package/dist/daemon/pid.d.ts +0 -31
  345. package/dist/daemon/pid.js +0 -212
  346. package/dist/daemon/route.d.ts +0 -14
  347. package/dist/daemon/route.js +0 -43
  348. package/dist/daemon/server.d.ts +0 -67
  349. package/dist/daemon/server.js +0 -563
  350. package/dist/daemon/supervise.d.ts +0 -29
  351. package/dist/daemon/supervise.js +0 -100
  352. package/dist/daemon/supervisor.d.ts +0 -91
  353. package/dist/daemon/supervisor.js +0 -612
  354. package/dist/daemon/types.d.ts +0 -71
  355. package/dist/daemon/types.js +0 -2
  356. package/dist/dinox.d.ts +0 -2
  357. package/dist/editor/anchor.d.ts +0 -46
  358. package/dist/editor/anchor.js +0 -129
  359. package/dist/editor/blockIds.d.ts +0 -21
  360. package/dist/editor/blockIds.js +0 -51
  361. package/dist/editor/blocks.d.ts +0 -47
  362. package/dist/editor/blocks.js +0 -236
  363. package/dist/editor/compat.d.ts +0 -32
  364. package/dist/editor/compat.js +0 -392
  365. package/dist/editor/daemon.d.ts +0 -10
  366. package/dist/editor/daemon.js +0 -56
  367. package/dist/editor/document.d.ts +0 -74
  368. package/dist/editor/document.js +0 -88
  369. package/dist/editor/i18n.d.ts +0 -23
  370. package/dist/editor/i18n.js +0 -61
  371. package/dist/editor/install.d.ts +0 -90
  372. package/dist/editor/install.js +0 -335
  373. package/dist/editor/mcp.d.ts +0 -22
  374. package/dist/editor/mcp.js +0 -222
  375. package/dist/editor/meta.d.ts +0 -70
  376. package/dist/editor/meta.js +0 -163
  377. package/dist/editor/paths.d.ts +0 -2
  378. package/dist/editor/paths.js +0 -13
  379. package/dist/editor/persistence.d.ts +0 -4
  380. package/dist/editor/persistence.js +0 -35
  381. package/dist/editor/saveGuard.d.ts +0 -9
  382. package/dist/editor/saveGuard.js +0 -38
  383. package/dist/editor/schema.d.ts +0 -14
  384. package/dist/editor/schema.js +0 -38
  385. package/dist/editor/service.d.ts +0 -326
  386. package/dist/editor/service.js +0 -1007
  387. package/dist/gateway/adapters/acp.d.ts +0 -75
  388. package/dist/gateway/adapters/acp.js +0 -431
  389. package/dist/gateway/adapters/codexImages.d.ts +0 -4
  390. package/dist/gateway/adapters/codexImages.js +0 -34
  391. package/dist/gateway/adapters/echo.d.ts +0 -12
  392. package/dist/gateway/adapters/echo.js +0 -54
  393. package/dist/gateway/adapters/index.d.ts +0 -13
  394. package/dist/gateway/adapters/index.js +0 -42
  395. package/dist/gateway/agentTaskHost.d.ts +0 -135
  396. package/dist/gateway/agentTaskHost.js +0 -410
  397. package/dist/gateway/assistantProjection.d.ts +0 -36
  398. package/dist/gateway/assistantProjection.js +0 -230
  399. package/dist/gateway/config.d.ts +0 -56
  400. package/dist/gateway/config.js +0 -312
  401. package/dist/gateway/conversationContext.d.ts +0 -44
  402. package/dist/gateway/conversationContext.js +0 -75
  403. package/dist/gateway/detect.d.ts +0 -63
  404. package/dist/gateway/detect.js +0 -281
  405. package/dist/gateway/deviceHost.d.ts +0 -100
  406. package/dist/gateway/deviceHost.js +0 -735
  407. package/dist/gateway/fileUpload.d.ts +0 -12
  408. package/dist/gateway/fileUpload.js +0 -154
  409. package/dist/gateway/keepAwake.d.ts +0 -24
  410. package/dist/gateway/keepAwake.js +0 -64
  411. package/dist/gateway/mcpCommandTools.d.ts +0 -62
  412. package/dist/gateway/mcpCommandTools.js +0 -220
  413. package/dist/gateway/mcpEnv.d.ts +0 -11
  414. package/dist/gateway/mcpEnv.js +0 -11
  415. package/dist/gateway/mcpGroups.d.ts +0 -3
  416. package/dist/gateway/mcpGroups.js +0 -4
  417. package/dist/gateway/mcpServer.d.ts +0 -25
  418. package/dist/gateway/mcpServer.js +0 -214
  419. package/dist/gateway/processTree.d.ts +0 -15
  420. package/dist/gateway/processTree.js +0 -60
  421. package/dist/gateway/protocol.d.ts +0 -145
  422. package/dist/gateway/protocol.js +0 -195
  423. package/dist/gateway/runExecutor.d.ts +0 -104
  424. package/dist/gateway/runExecutor.js +0 -480
  425. package/dist/gateway/service.d.ts +0 -35
  426. package/dist/gateway/service.js +0 -147
  427. package/dist/gateway/spawnAgent.d.ts +0 -12
  428. package/dist/gateway/spawnAgent.js +0 -32
  429. package/dist/gateway/streamPublisher.d.ts +0 -33
  430. package/dist/gateway/streamPublisher.js +0 -93
  431. package/dist/gateway/taskJournal.d.ts +0 -14
  432. package/dist/gateway/taskJournal.js +0 -47
  433. package/dist/gateway/threadStore.d.ts +0 -230
  434. package/dist/gateway/threadStore.js +0 -621
  435. package/dist/gateway/types.d.ts +0 -168
  436. package/dist/gateway/types.js +0 -12
  437. package/dist/gateway/workspace.d.ts +0 -5
  438. package/dist/gateway/workspace.js +0 -30
  439. package/dist/gateway/workspaceFolders.d.ts +0 -35
  440. package/dist/gateway/workspaceFolders.js +0 -142
  441. package/dist/gateway/workspaceListing.d.ts +0 -5
  442. package/dist/gateway/workspaceListing.js +0 -78
  443. package/dist/integrations/dsh/host.d.ts +0 -53
  444. package/dist/integrations/dsh/host.js +0 -237
  445. package/dist/integrations/dsh/mcpClient.d.ts +0 -66
  446. package/dist/integrations/dsh/mcpClient.js +0 -192
  447. package/dist/powersync/connector.d.ts +0 -22
  448. package/dist/powersync/connector.js +0 -91
  449. package/dist/powersync/exclusiveRuntime.d.ts +0 -21
  450. package/dist/powersync/exclusiveRuntime.js +0 -66
  451. package/dist/powersync/runtime.d.ts +0 -62
  452. package/dist/powersync/runtime.js +0 -358
  453. package/dist/powersync/schema/content.d.ts +0 -1
  454. package/dist/powersync/schema/content.js +0 -1
  455. package/dist/powersync/schema/electronCanonical.d.ts +0 -1561
  456. package/dist/powersync/schema/electronCanonical.js +0 -1154
  457. package/dist/powersync/schema/index.d.ts +0 -844
  458. package/dist/powersync/schema/index.js +0 -8
  459. package/dist/powersync/schema/local.d.ts +0 -13
  460. package/dist/powersync/schema/local.js +0 -24
  461. package/dist/powersync/schema/note.d.ts +0 -1
  462. package/dist/powersync/schema/note.js +0 -1
  463. package/dist/powersync/schema/notesExtras.d.ts +0 -1
  464. package/dist/powersync/schema/notesExtras.js +0 -1
  465. package/dist/powersync/schema/projects.d.ts +0 -1
  466. package/dist/powersync/schema/projects.js +0 -1
  467. package/dist/powersync/schema/savedViews.d.ts +0 -1
  468. package/dist/powersync/schema/savedViews.js +0 -1
  469. package/dist/powersync/schema/storage.d.ts +0 -1
  470. package/dist/powersync/schema/storage.js +0 -1
  471. package/dist/powersync/schema/tags.d.ts +0 -1
  472. package/dist/powersync/schema/tags.js +0 -1
  473. package/dist/powersync/syncGate.d.ts +0 -45
  474. package/dist/powersync/syncGate.js +0 -45
  475. package/dist/powersync/syncPass.d.ts +0 -9
  476. package/dist/powersync/syncPass.js +0 -33
  477. package/dist/powersync/tokenIndex.d.ts +0 -32
  478. package/dist/powersync/tokenIndex.js +0 -382
  479. package/dist/powersync/uploader.d.ts +0 -22
  480. package/dist/powersync/uploader.js +0 -231
  481. package/dist/requests/execute.d.ts +0 -11
  482. package/dist/requests/execute.js +0 -26
  483. package/dist/requests/store.d.ts +0 -10
  484. package/dist/requests/store.js +0 -190
  485. package/dist/runCli.d.ts +0 -2
  486. package/dist/runCli.js +0 -64
  487. package/dist/skills/check.d.ts +0 -7
  488. package/dist/skills/check.js +0 -747
  489. package/dist/skills/commandRefs.d.ts +0 -21
  490. package/dist/skills/commandRefs.js +0 -124
  491. package/dist/skills/generate.d.ts +0 -13
  492. package/dist/skills/generate.js +0 -80
  493. package/dist/skills/registry.d.ts +0 -13
  494. package/dist/skills/registry.js +0 -65
  495. package/dist/skills/retired.d.ts +0 -60
  496. package/dist/skills/retired.js +0 -58
  497. package/dist/utils/abort.d.ts +0 -6
  498. package/dist/utils/abort.js +0 -19
  499. package/dist/utils/argValue.d.ts +0 -1
  500. package/dist/utils/argValue.js +0 -18
  501. package/dist/utils/asyncRelease.d.ts +0 -2
  502. package/dist/utils/asyncRelease.js +0 -25
  503. package/dist/utils/authToken.d.ts +0 -4
  504. package/dist/utils/authToken.js +0 -28
  505. package/dist/utils/bidlinkCanonicalization.d.ts +0 -2
  506. package/dist/utils/bidlinkCanonicalization.js +0 -164
  507. package/dist/utils/consoleEncoding.d.ts +0 -5
  508. package/dist/utils/consoleEncoding.js +0 -27
  509. package/dist/utils/cursor.d.ts +0 -9
  510. package/dist/utils/cursor.js +0 -61
  511. package/dist/utils/deadline.d.ts +0 -8
  512. package/dist/utils/deadline.js +0 -31
  513. package/dist/utils/defaultFormat.d.ts +0 -8
  514. package/dist/utils/defaultFormat.js +0 -38
  515. package/dist/utils/dryRun.d.ts +0 -32
  516. package/dist/utils/dryRun.js +0 -88
  517. package/dist/utils/errorCodes.d.ts +0 -595
  518. package/dist/utils/errorCodes.js +0 -163
  519. package/dist/utils/errors.d.ts +0 -54
  520. package/dist/utils/errors.js +0 -277
  521. package/dist/utils/id.d.ts +0 -1
  522. package/dist/utils/id.js +0 -4
  523. package/dist/utils/nodeRuntime.d.ts +0 -4
  524. package/dist/utils/nodeRuntime.js +0 -12
  525. package/dist/utils/output.d.ts +0 -26
  526. package/dist/utils/output.js +0 -262
  527. package/dist/utils/processExit.d.ts +0 -1
  528. package/dist/utils/processExit.js +0 -33
  529. package/dist/utils/progress.d.ts +0 -25
  530. package/dist/utils/progress.js +0 -59
  531. package/dist/utils/redact.d.ts +0 -1
  532. package/dist/utils/redact.js +0 -10
  533. package/dist/utils/requestContext.d.ts +0 -32
  534. package/dist/utils/requestContext.js +0 -13
  535. package/dist/utils/select.d.ts +0 -20
  536. package/dist/utils/select.js +0 -92
  537. package/dist/utils/sqliteLease.d.ts +0 -8
  538. package/dist/utils/sqliteLease.js +0 -59
  539. package/dist/utils/syncTimeout.d.ts +0 -7
  540. package/dist/utils/syncTimeout.js +0 -20
  541. package/dist/utils/terminalSanitization.d.ts +0 -2
  542. package/dist/utils/terminalSanitization.js +0 -37
  543. package/dist/utils/text.d.ts +0 -1
  544. package/dist/utils/text.js +0 -35
  545. package/dist/utils/time.d.ts +0 -1
  546. package/dist/utils/time.js +0 -3
  547. package/dist/utils/tiptapMarkdown.d.ts +0 -9
  548. package/dist/utils/tiptapMarkdown.js +0 -367
  549. package/dist/utils/tiptapMarkdownSchema.d.ts +0 -37
  550. package/dist/utils/tiptapMarkdownSchema.js +0 -608
  551. package/dist/utils/tiptapMarkdownSchemaUtils.d.ts +0 -74
  552. package/dist/utils/tiptapMarkdownSchemaUtils.js +0 -394
  553. package/dist/utils/tiptapMarkdownSyntax.d.ts +0 -9
  554. package/dist/utils/tiptapMarkdownSyntax.js +0 -249
  555. package/dist/utils/tokenize.d.ts +0 -1
  556. package/dist/utils/tokenize.js +0 -67
  557. package/dist/utils/updateNotice.d.ts +0 -8
  558. package/dist/utils/updateNotice.js +0 -112
  559. package/dist/utils/usageError.d.ts +0 -37
  560. package/dist/utils/usageError.js +0 -127
  561. package/dist/utils/version.d.ts +0 -1
  562. package/dist/utils/version.js +0 -21
  563. package/dist/vendor/electron/domain/note-templates.d.ts +0 -3
  564. package/dist/vendor/electron/domain/note-templates.js +0 -232
  565. package/dist/vendor/electron/domain/properties.d.ts +0 -10
  566. package/dist/vendor/electron/domain/properties.js +0 -1549
  567. package/dist/vendor/electron/domain/saved-view-analytics.d.ts +0 -45
  568. package/dist/vendor/electron/domain/saved-view-analytics.js +0 -365
  569. package/dist/vendor/electron/domain/saved-view-relative-date.d.ts +0 -21
  570. package/dist/vendor/electron/domain/saved-view-relative-date.js +0 -153
  571. package/dist/vendor/electron/domain/saved-views.d.ts +0 -61
  572. package/dist/vendor/electron/domain/saved-views.js +0 -1120
  573. package/dist/vendor/electron/rpc.d.ts +0 -22
  574. package/dist/vendor/electron/rpc.js +0 -27
  575. package/dist/vendor/electron/shared/ai-errors.d.ts +0 -11
  576. package/dist/vendor/electron/shared/ai-errors.js +0 -107
  577. package/dist/vendor/electron/shared/external-types.d.ts +0 -20
  578. package/dist/vendor/electron/shared/external-types.js +0 -1
  579. package/dist/vendor/electron/shared/index.d.ts +0 -9
  580. package/dist/vendor/electron/shared/index.js +0 -7
  581. package/dist/vendor/electron/shared/note-properties.d.ts +0 -328
  582. package/dist/vendor/electron/shared/note-properties.js +0 -1027
  583. package/dist/vendor/electron/shared/note-templates.d.ts +0 -82
  584. package/dist/vendor/electron/shared/note-templates.js +0 -84
  585. package/dist/vendor/electron/shared/powersync-read-models.d.ts +0 -1716
  586. package/dist/vendor/electron/shared/powersync-read-models.js +0 -1
  587. package/dist/vendor/electron/shared/remote-device-agent.d.ts +0 -375
  588. package/dist/vendor/electron/shared/remote-device-agent.js +0 -191
  589. package/dist/vendor/electron/shared/saved-views.d.ts +0 -394
  590. package/dist/vendor/electron/shared/saved-views.js +0 -981
  591. package/dist/vendor/electron/sql-utils.d.ts +0 -5
  592. package/dist/vendor/electron/sql-utils.js +0 -32
@@ -0,0 +1,1551 @@
1
+ import { createRequire as __dinoxCreateRequire } from 'node:module';
2
+ const require = __dinoxCreateRequire(import.meta.url);
3
+ import {
4
+ WechatArticleToMarkdownError,
5
+ assertWechatArticleUrl,
6
+ canonicalWechatUrl,
7
+ wechatErrorCodeForCaptureBlockReason
8
+ } from "./chunk-FKLZZGEX.js";
9
+ import {
10
+ extractHtmlTablesToMarkdown,
11
+ restoreTablePlaceholders
12
+ } from "./chunk-PJDD4R46.js";
13
+ import {
14
+ detectCaptureBlock,
15
+ isDecorativeEmojiImage
16
+ } from "./chunk-N44NRKDJ.js";
17
+ import {
18
+ useFlatInlineFormatting
19
+ } from "./chunk-RKJYKUQD.js";
20
+ import {
21
+ launchBrowser
22
+ } from "./chunk-W7R5JTSA.js";
23
+ import {
24
+ summarizeImageFailures
25
+ } from "./chunk-5KU25TMX.js";
26
+ import {
27
+ isTransientError,
28
+ retry
29
+ } from "./chunk-QZQRG3JY.js";
30
+ import {
31
+ normalizeClipMarkdownBody,
32
+ stripClipBoilerplate
33
+ } from "./chunk-XMMTGPZ6.js";
34
+ import "./chunk-URYABAYN.js";
35
+ import {
36
+ clipEngineConfig
37
+ } from "./chunk-F7BDWXBG.js";
38
+ import {
39
+ formatClipFooter
40
+ } from "./chunk-AHRCI2RW.js";
41
+ import {
42
+ replaceRemoteMarkdownImageUrls
43
+ } from "./chunk-6VMHHE5Y.js";
44
+ import {
45
+ logInfo,
46
+ logWarn
47
+ } from "./chunk-KOAKG2QU.js";
48
+ import "./chunk-XQZUX7OT.js";
49
+
50
+ // ../../packages/clip-engine/src/wechatArticleToMarkdown/assets.ts
51
+ import { mkdir, writeFile } from "node:fs/promises";
52
+ import { dirname, join } from "node:path";
53
+ import { posix } from "node:path";
54
+ var DEFAULT_IMAGE_CONCURRENCY = 5;
55
+ var DEFAULT_TIMEOUT_MS = 15e3;
56
+ var DEFAULT_MAX_IMAGE_BYTES = 20 * 1024 * 1024;
57
+ var DEFAULT_RETRIES = 3;
58
+ var DEFAULT_REFERER = "https://mp.weixin.qq.com/";
59
+ var DEFAULT_USER_AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36";
60
+ var DEFAULT_IMAGE_PATH_PREFIX = "images";
61
+ var PNG_MAGIC = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
62
+ async function downloadWechatArticleImages(options) {
63
+ const urls = unique(options.imageUrls);
64
+ if (!urls.length) return emptyResult();
65
+ await mkdir(options.imageDir, { recursive: true });
66
+ const fetcher = options.fetcher ?? fetch;
67
+ const concurrency = Math.max(1, options.concurrency ?? DEFAULT_IMAGE_CONCURRENCY);
68
+ const results = await mapWithConcurrency(
69
+ urls,
70
+ concurrency,
71
+ async (remoteUrl, index) => downloadOneImage(remoteUrl, index + 1, options, fetcher)
72
+ );
73
+ const downloaded = [];
74
+ const failed = [];
75
+ for (const result of results) {
76
+ if ("download" in result) downloaded.push(result.download);
77
+ else failed.push(result.failure);
78
+ }
79
+ return {
80
+ downloaded,
81
+ failed,
82
+ urlMap: new Map(downloaded.map((item) => [item.remoteUrl, item.localPath]))
83
+ };
84
+ }
85
+ function emptyResult() {
86
+ return {
87
+ downloaded: [],
88
+ failed: [],
89
+ urlMap: /* @__PURE__ */ new Map()
90
+ };
91
+ }
92
+ async function downloadOneImage(remoteUrl, index, options, fetcher) {
93
+ try {
94
+ const fetchUrl = normalizeFetchUrl(remoteUrl);
95
+ const { buffer, contentType } = await fetchImageWithFallback(fetcher, fetchUrl, options);
96
+ const fileName = `img_${String(index).padStart(3, "0")}.${detectImageExtension(buffer, contentType, fetchUrl)}`;
97
+ const localPath = posix.join(options.imagePathPrefix ?? DEFAULT_IMAGE_PATH_PREFIX, fileName);
98
+ const filePath = join(options.imageDir, ...localPath.split("/"));
99
+ await mkdir(dirname(filePath), { recursive: true });
100
+ await writeFile(filePath, buffer);
101
+ return {
102
+ download: {
103
+ bytes: buffer.byteLength,
104
+ fileName,
105
+ localPath,
106
+ remoteUrl
107
+ }
108
+ };
109
+ } catch (error) {
110
+ return {
111
+ failure: {
112
+ message: error instanceof Error ? error.message : String(error),
113
+ remoteUrl
114
+ }
115
+ };
116
+ }
117
+ }
118
+ async function fetchImageWithFallback(fetcher, fetchUrl, options) {
119
+ const fetchOnce = (url) => retry(() => fetchImage(fetcher, url, options), {
120
+ attempts: Math.max(1, options.retries ?? DEFAULT_RETRIES),
121
+ isRetryable: isTransientError
122
+ });
123
+ const smaller = smallerWechatVariant(fetchUrl);
124
+ if (!smaller) return fetchOnce(fetchUrl);
125
+ try {
126
+ return await fetchOnce(fetchUrl);
127
+ } catch (error) {
128
+ return fetchOnce(smaller).catch(() => {
129
+ throw error;
130
+ });
131
+ }
132
+ }
133
+ function smallerWechatVariant(url) {
134
+ try {
135
+ const parsed = new URL(url);
136
+ if (!isWechatImageHost(parsed.hostname) || !/\/0$/.test(parsed.pathname)) return null;
137
+ parsed.pathname = parsed.pathname.replace(/\/0$/, "/640");
138
+ return parsed.toString();
139
+ } catch {
140
+ return null;
141
+ }
142
+ }
143
+ async function fetchImage(fetcher, url, options) {
144
+ const response = await fetchWithTimeout(fetcher, url, options);
145
+ if (!response.ok) {
146
+ const error = new Error(`HTTP ${response.status}`);
147
+ error.status = response.status;
148
+ throw error;
149
+ }
150
+ const maxImageBytes = options.maxImageBytes ?? DEFAULT_MAX_IMAGE_BYTES;
151
+ const contentLength = Number.parseInt(response.headers.get("content-length") ?? "", 10);
152
+ if (Number.isFinite(contentLength) && contentLength > maxImageBytes) {
153
+ throw new Error(`image exceeds max size (${contentLength}/${maxImageBytes})`);
154
+ }
155
+ const buffer = Buffer.from(await response.arrayBuffer());
156
+ if (buffer.byteLength > maxImageBytes) {
157
+ throw new Error(`image exceeds max size (${buffer.byteLength}/${maxImageBytes})`);
158
+ }
159
+ return {
160
+ buffer,
161
+ contentType: response.headers.get("content-type") ?? ""
162
+ };
163
+ }
164
+ async function fetchWithTimeout(fetcher, url, options) {
165
+ const controller = new AbortController();
166
+ const timer = setTimeout(() => controller.abort(), options.timeoutMs ?? DEFAULT_TIMEOUT_MS);
167
+ try {
168
+ return await fetcher(url, {
169
+ headers: {
170
+ "User-Agent": DEFAULT_USER_AGENT,
171
+ Referer: options.referer ?? DEFAULT_REFERER
172
+ },
173
+ signal: controller.signal
174
+ });
175
+ } finally {
176
+ clearTimeout(timer);
177
+ }
178
+ }
179
+ function normalizeFetchUrl(url) {
180
+ const withProtocol = url.startsWith("//") ? `https:${url}` : url;
181
+ try {
182
+ const parsed = new URL(withProtocol);
183
+ parsed.hash = "";
184
+ if (isWechatImageHost(parsed.hostname)) {
185
+ parsed.searchParams.delete("tp");
186
+ }
187
+ return parsed.toString();
188
+ } catch {
189
+ return withProtocol;
190
+ }
191
+ }
192
+ function isWechatImageHost(hostname) {
193
+ const host = hostname.toLowerCase();
194
+ return host === "mmbiz.qpic.cn" || host.endsWith(".qpic.cn") || host.endsWith(".weixin.qq.com");
195
+ }
196
+ function detectImageExtension(buffer, contentType, url) {
197
+ const fromMagic = extensionFromMagic(buffer);
198
+ if (fromMagic) return fromMagic;
199
+ const fromContentType = extensionFromContentType(contentType);
200
+ if (fromContentType) return fromContentType;
201
+ return inferImageExtension(url);
202
+ }
203
+ function extensionFromMagic(buffer) {
204
+ if (buffer.length >= 12 && buffer.subarray(0, 4).toString("latin1") === "RIFF" && buffer.subarray(8, 12).toString("latin1") === "WEBP") {
205
+ return "webp";
206
+ }
207
+ if (buffer.length >= 3 && buffer[0] === 255 && buffer[1] === 216 && buffer[2] === 255) return "jpg";
208
+ if (buffer.length >= 8 && buffer.subarray(0, 8).equals(PNG_MAGIC)) return "png";
209
+ if (buffer.length >= 6) {
210
+ const header = buffer.subarray(0, 6).toString("latin1");
211
+ if (header === "GIF87a" || header === "GIF89a") return "gif";
212
+ }
213
+ return null;
214
+ }
215
+ function extensionFromContentType(contentType) {
216
+ const mime = contentType.split(";")[0]?.trim().toLowerCase() ?? "";
217
+ if (mime === "image/jpeg" || mime === "image/jpg") return "jpg";
218
+ if (mime === "image/png") return "png";
219
+ if (mime === "image/gif") return "gif";
220
+ if (mime === "image/webp") return "webp";
221
+ if (mime === "image/avif") return "avif";
222
+ return null;
223
+ }
224
+ function inferImageExtension(url) {
225
+ const wxFormat = url.match(/[?&]wx_fmt=([a-z0-9]+)/i)?.[1];
226
+ const pathFormat = url.match(/\.([a-z0-9]{3,4})(?:[?#]|$)/i)?.[1];
227
+ const extension = (wxFormat ?? pathFormat ?? "png").toLowerCase();
228
+ return extension === "jpeg" ? "jpg" : extension.replace(/[^a-z0-9]/g, "") || "png";
229
+ }
230
+ async function mapWithConcurrency(items, concurrency, mapper) {
231
+ const results = new Array(items.length);
232
+ let cursor = 0;
233
+ const workers = Array.from({ length: Math.min(concurrency, items.length) }, async () => {
234
+ while (cursor < items.length) {
235
+ const index = cursor;
236
+ cursor += 1;
237
+ results[index] = await mapper(items[index], index);
238
+ }
239
+ });
240
+ await Promise.all(workers);
241
+ return results;
242
+ }
243
+ function unique(values) {
244
+ const seen = /* @__PURE__ */ new Set();
245
+ const output = [];
246
+ for (const value of values) {
247
+ const normalized = value.trim();
248
+ if (!normalized || seen.has(normalized)) continue;
249
+ seen.add(normalized);
250
+ output.push(normalized);
251
+ }
252
+ return output;
253
+ }
254
+
255
+ // ../../packages/clip-engine/src/wechatArticleToMarkdown/parse.ts
256
+ import * as cheerio from "cheerio";
257
+
258
+ // ../../packages/clip-engine/src/wechatArticleToMarkdown/layout.ts
259
+ var BLOCK_CHILD_SELECTOR = "p, table, ul, ol, blockquote, h1, h2, h3, h4, h5, h6, pre";
260
+ var HEADING_MARK_RE = /^(?:[一二三四五六七八九十百千]+[、..]|\d+[.、])/;
261
+ var FONT_WEIGHT_HEADING_RE = /font-weight\s*:\s*(?:bold|[7-9]00)/i;
262
+ var FONT_SIZE_RE = /font-size\s*:\s*(\d+(?:\.\d+)?)/i;
263
+ function flattenWechatEditorLayout($, content) {
264
+ unwrapEditorSections($, content);
265
+ unwrapLeafSpans($, content);
266
+ unwrapLayoutTables($, content);
267
+ pruneEmptyEditorNodes($, content);
268
+ }
269
+ function unwrapEditorSections($, content) {
270
+ for (const element of content.find("section").toArray().reverse()) {
271
+ const node = $(element);
272
+ if (node.find(BLOCK_CHILD_SELECTOR).length) {
273
+ node.replaceWith(node.contents());
274
+ continue;
275
+ }
276
+ const inner = (node.html() ?? "").trim();
277
+ if (!inner) {
278
+ node.remove();
279
+ continue;
280
+ }
281
+ node.replaceWith(`<p>${inner}</p>`);
282
+ }
283
+ }
284
+ function unwrapLeafSpans($, content) {
285
+ for (const element of content.find("span").toArray().reverse()) {
286
+ const node = $(element);
287
+ if (node.attr("leaf") === void 0) continue;
288
+ node.replaceWith(node.contents());
289
+ }
290
+ }
291
+ function unwrapLayoutTables($, content) {
292
+ while (true) {
293
+ const leaves = content.find("table").toArray().filter((element) => $(element).find("table").length === 0);
294
+ let changed = false;
295
+ for (const element of leaves) {
296
+ const table = $(element);
297
+ if (isTabularDataTable($, table)) continue;
298
+ const replacement = layoutTableReplacement($, table);
299
+ if (replacement) table.replaceWith(replacement);
300
+ else table.remove();
301
+ changed = true;
302
+ }
303
+ if (!changed) break;
304
+ }
305
+ }
306
+ function isTabularDataTable($, table) {
307
+ const rows = collectDirectRows($, table);
308
+ const columns = Math.max(0, ...rows.map((row) => row.length));
309
+ return columns >= 2 && rows.length >= 2;
310
+ }
311
+ function layoutTableReplacement($, table) {
312
+ const rows = collectDirectRows($, table);
313
+ if (!rows.length) return "";
314
+ if (rows.length === 1 && rows[0]?.length === 1) {
315
+ const cell = rows[0][0];
316
+ if (!cell) return "";
317
+ const text = normalizeLayoutText(cell.text());
318
+ if (looksLikeHeading(table, cell, text)) return `<h2>${escapeHtmlText(text)}</h2>`;
319
+ const inner = (cell.html() ?? "").trim();
320
+ if (isCalloutCell(table, cell)) return `<blockquote>${inner}</blockquote>`;
321
+ return inner;
322
+ }
323
+ if (rows.length === 1 && (rows[0]?.length ?? 0) >= 2) {
324
+ const parts = (rows[0] ?? []).map((cell) => collapseCellToInlineHtml(cell)).filter(Boolean);
325
+ return parts.length ? `<p>${parts.join(" ")}</p>` : "";
326
+ }
327
+ return rows.map((cells) => cells.map((cell) => (cell.html() ?? "").trim()).join("")).join("");
328
+ }
329
+ function looksLikeHeading(table, cell, text) {
330
+ if (!text || text.length > 48 || cell.find("img").length) return false;
331
+ if (HEADING_MARK_RE.test(text)) return true;
332
+ const style = combinedStyle(table, cell);
333
+ if (FONT_WEIGHT_HEADING_RE.test(style)) return true;
334
+ const fontSize = Number(style.match(FONT_SIZE_RE)?.[1]);
335
+ return Number.isFinite(fontSize) && fontSize >= 16;
336
+ }
337
+ function isCalloutCell(table, cell) {
338
+ return /border-left/i.test(combinedStyle(table, cell));
339
+ }
340
+ function combinedStyle(table, cell) {
341
+ return `${table.attr("style") ?? ""} ${cell.attr("style") ?? ""}`;
342
+ }
343
+ function collapseCellToInlineHtml(cell) {
344
+ const children = cell.children();
345
+ if (children.length === 1) {
346
+ const tag = String(children.prop("tagName") ?? "").toLowerCase();
347
+ if (tag === "p" || tag === "section" || tag === "div") return (children.html() ?? "").trim();
348
+ }
349
+ return (cell.html() ?? "").trim();
350
+ }
351
+ function collectDirectRows($, table) {
352
+ const rows = [];
353
+ directTableRows(table).each((_, tr) => {
354
+ const cells = $(tr).children("td, th").toArray().map((cell) => $(cell));
355
+ if (cells.length) rows.push(cells);
356
+ });
357
+ return rows;
358
+ }
359
+ function directTableRows(table) {
360
+ return table.children("thead, tbody, tfoot").children("tr").add(table.children("tr"));
361
+ }
362
+ function pruneEmptyEditorNodes($, content) {
363
+ for (const element of content.find("p, span, div").toArray().reverse()) {
364
+ const node = $(element);
365
+ if (node.find("img, video, audio, iframe, a").length) continue;
366
+ const text = normalizeLayoutText(node.text());
367
+ const html = (node.html() ?? "").replace(/<br\s*\/?>/gi, "").trim();
368
+ if (!text && !html) node.remove();
369
+ }
370
+ }
371
+ function normalizeLayoutText(value) {
372
+ return value.replace(/\u00a0/g, " ").replace(/\s+/g, " ").trim();
373
+ }
374
+ function escapeHtmlText(value) {
375
+ return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
376
+ }
377
+
378
+ // ../../packages/clip-engine/src/wechatArticleToMarkdown/time.ts
379
+ function extractWechatPublishTime(html) {
380
+ const jsDecoded = html.match(/create_time\s*:\s*JsDecode\('([^']+)'\)/);
381
+ if (jsDecoded?.[1]) return formatCreateTimeValue(jsDecoded[1]);
382
+ const quoted = html.match(/create_time\s*:\s*'(\d+)'/);
383
+ if (quoted?.[1]) return formatUnixTimestamp(Number.parseInt(quoted[1], 10));
384
+ const assigned = html.match(/create_time\s*[:=]\s*["']?(\d+)["']?/);
385
+ if (assigned?.[1]) return formatUnixTimestamp(Number.parseInt(assigned[1], 10));
386
+ return "";
387
+ }
388
+ function formatCreateTimeValue(value) {
389
+ const timestamp = Number.parseInt(value, 10);
390
+ return Number.isFinite(timestamp) && timestamp > 0 ? formatUnixTimestamp(timestamp) : value;
391
+ }
392
+ function formatUnixTimestamp(timestamp) {
393
+ const chinaOffsetSeconds = 8 * 60 * 60;
394
+ const date = new Date((timestamp + chinaOffsetSeconds) * 1e3);
395
+ return date.toISOString().slice(0, 19).replace("T", " ");
396
+ }
397
+
398
+ // ../../packages/clip-engine/src/wechatArticleToMarkdown/parse.ts
399
+ var ENCODED_ANCHOR_RE = /&lt;a\b[\s\S]*?&gt;[\s\S]*?&lt;\/a&gt;/gi;
400
+ var IMAGE_SOURCE_ATTRS = ["data-src", "data-original", "data-lazy-src", "data-url", "data-backsrc", "src"];
401
+ var EXPIRED_PATTERNS = [
402
+ "\u6B64\u5185\u5BB9\u56E0\u8FDD\u89C4\u65E0\u6CD5\u67E5\u770B",
403
+ "\u8BE5\u5185\u5BB9\u5DF2\u88AB\u53D1\u5E03\u8005\u5220\u9664",
404
+ "\u94FE\u63A5\u5DF2\u8FC7\u671F",
405
+ "\u8BE5\u516C\u4F17\u53F7\u5DF2\u6CE8\u9500",
406
+ "\u6B64\u5185\u5BB9\u88AB\u6295\u8BC9\u4E14\u7ECF\u5BA1\u6838\u6D89\u5ACC\u4FB5\u6743",
407
+ "\u6B64\u5E10\u53F7\u5DF2\u88AB\u5C4F\u853D",
408
+ "\u8BE5\u5185\u5BB9\u5DF2\u88AB\u9650\u5236\u8BBF\u95EE",
409
+ "\u6B64\u5185\u5BB9\u53D1\u9001\u5931\u8D25\u65E0\u6CD5\u67E5\u770B"
410
+ ];
411
+ function parseWechatArticleHtml(html, options = {}) {
412
+ if (isWechatContentExpired(html)) {
413
+ throw new WechatArticleToMarkdownError("CONTENT_EXPIRED", "WeChat article is expired or unavailable", {
414
+ url: options.sourceUrl
415
+ });
416
+ }
417
+ const $ = cheerio.load(html);
418
+ const metaTitle = normalizeTitle(readMeta($, "og:title") || $("title").first().text());
419
+ const imageShare = extractWechatImageShareData(html, metaTitle);
420
+ const content = extractWechatContent($, html, imageShare);
421
+ const metadata = extractMetadata($, html, {
422
+ imageShare,
423
+ metaTitle,
424
+ sourceUrl: options.sourceUrl ?? ""
425
+ });
426
+ if (!metadata.title) {
427
+ throw new WechatArticleToMarkdownError("TITLE_NOT_FOUND", "could not extract WeChat article title");
428
+ }
429
+ if (!content.html.trim()) {
430
+ throw new WechatArticleToMarkdownError("CONTENT_NOT_FOUND", "could not extract WeChat article content");
431
+ }
432
+ return {
433
+ codeBlocks: content.codeBlocks,
434
+ contentHtml: content.html,
435
+ imageUrls: collectImageUrls(content.html),
436
+ metadata
437
+ };
438
+ }
439
+ function extractWechatContent($, html, imageShare) {
440
+ const hasArticleNode = selectMainContent($).length > 0;
441
+ const hasLegacySwiperNode = $(".swiper_item_img").length > 0;
442
+ const pageKind = detectPageKind({
443
+ hasArticleNode,
444
+ hasImageSharePictures: imageShare.pictures.length > 0,
445
+ hasImageShareType: isWechatImageShareType(imageShare),
446
+ hasLegacySwiperNode
447
+ });
448
+ if (pageKind === "image_share") {
449
+ return {
450
+ codeBlocks: [],
451
+ html: sanitizeEncodedAnchors(buildWechatImageShareHtml(imageShare)),
452
+ pageKind
453
+ };
454
+ }
455
+ if (pageKind === "legacy_image_swiper") {
456
+ return {
457
+ codeBlocks: [],
458
+ html: extractLegacySwiperHtml($, html),
459
+ pageKind
460
+ };
461
+ }
462
+ const content = selectMainContent($);
463
+ if (!content.length) {
464
+ return {
465
+ codeBlocks: [],
466
+ html: "",
467
+ pageKind
468
+ };
469
+ }
470
+ content.find("script, style").remove();
471
+ transformChannelsVideos($, content);
472
+ normalizeImages($, content);
473
+ const codeBlocks = extractCodeBlocks($, content);
474
+ sanitizeAnchors($, content);
475
+ removeNoise(content);
476
+ flattenWechatEditorLayout($, content);
477
+ transformInlineBreaks($, content);
478
+ return {
479
+ codeBlocks,
480
+ html: sanitizeEncodedAnchors(content.html() ?? "").trim(),
481
+ pageKind
482
+ };
483
+ }
484
+ function detectPageKind(input) {
485
+ if (input.hasImageShareType) return "image_share";
486
+ if (input.hasArticleNode) return "article";
487
+ if (input.hasImageSharePictures) return "image_share";
488
+ if (input.hasLegacySwiperNode) return "legacy_image_swiper";
489
+ return "unknown";
490
+ }
491
+ function selectMainContent($) {
492
+ const primary = $("#js_content").first();
493
+ if (primary.length) return primary;
494
+ return $(".rich_media_content").first();
495
+ }
496
+ function extractMetadata($, html, input) {
497
+ const sourceUrl = input.sourceUrl || normalizeWechatUrl(readMeta($, "og:url")) || "";
498
+ return {
499
+ author: normalizeText($("#js_name").first().text()) || input.imageShare.author || extractWechatJsString(html, "nick_name") || extractWechatJsString(html, "nickname") || normalizeText($('meta[name="author"]').first().attr("content") ?? ""),
500
+ publishTime: extractWechatPublishTime(html) || input.imageShare.publishTime || formatWechatTimestamp(extractWechatJsNumber(html, "ori_create_time") ?? extractWechatJsNumber(html, "ct")),
501
+ sourceUrl,
502
+ title: normalizeTitle($("#activity-name").first().text()) || input.imageShare.title || input.metaTitle || normalizeTitle(extractWechatJsString(html, "msg_title") || extractWechatJsString(html, "title"))
503
+ };
504
+ }
505
+ var CHANNELS_VIDEO_SELECTOR = "mp-common-videosnap, .videosnap_video_iframe";
506
+ var CHANNELS_VIDEO_NOTE = "\uFF08\u89C6\u9891\u53F7\u89C6\u9891\uFF0C\u6682\u4E0D\u652F\u6301\u81EA\u52A8\u4E0B\u8F7D\uFF0C\u8BF7\u5728\u5FAE\u4FE1\u4E2D\u67E5\u770B\uFF09";
507
+ function transformChannelsVideos($, content) {
508
+ content.find(CHANNELS_VIDEO_SELECTOR).each((_, element) => {
509
+ const node = $(element);
510
+ const nickname = normalizeText(node.attr("data-nickname") ?? "");
511
+ const descLines = decodeHtmlEntities(node.attr("data-desc") ?? "").replace(/\r/g, "").split(/\n+/).map((line) => line.trim()).filter(Boolean);
512
+ const heading = nickname ? `\u{1F3AC} \u89C6\u9891\u53F7\u89C6\u9891\uFF1A${nickname}` : "\u{1F3AC} \u89C6\u9891\u53F7\u89C6\u9891";
513
+ const parts = [`<p>${escapeHtmlText2(heading)}</p>`];
514
+ if (descLines.length) parts.push(`<p>${descLines.map(escapeHtmlText2).join("<br>")}</p>`);
515
+ parts.push(`<p>${escapeHtmlText2(CHANNELS_VIDEO_NOTE)}</p>`);
516
+ node.replaceWith(`<blockquote>${parts.join("")}</blockquote>`);
517
+ });
518
+ }
519
+ function normalizeImages($, content) {
520
+ content.find("img").each((_, element) => {
521
+ const image = $(element);
522
+ const src = normalizeWechatImageUrl(readPreferredImageSource(image));
523
+ if (!src) {
524
+ image.remove();
525
+ return;
526
+ }
527
+ const size = readImageSize(image);
528
+ if (isDecorativeEmojiImage({
529
+ alt: image.attr("alt"),
530
+ className: image.attr("class"),
531
+ height: size.height,
532
+ role: image.attr("role"),
533
+ src,
534
+ title: image.attr("title"),
535
+ width: size.width
536
+ })) {
537
+ image.remove();
538
+ return;
539
+ }
540
+ image.attr("src", src);
541
+ for (const key of Object.keys(image.attr() ?? {})) {
542
+ if (key.startsWith("data-") && key !== "data-src") image.removeAttr(key);
543
+ }
544
+ });
545
+ }
546
+ function readPreferredImageSource(image) {
547
+ for (const attr of IMAGE_SOURCE_ATTRS) {
548
+ const value = image.attr(attr)?.trim();
549
+ if (value && !isPlaceholderImageSrc(value)) return value;
550
+ }
551
+ return "";
552
+ }
553
+ function readImageSize(image) {
554
+ const style = image.attr("style") ?? "";
555
+ const width = readPositiveNumber(image.attr("width")) ?? readPositiveNumber(image.attr("data-w")) ?? readStyleDimension(style, "width");
556
+ const height = readPositiveNumber(image.attr("height")) ?? readStyleDimension(style, "height") ?? deriveHeightFromRatio(width, readPositiveNumber(image.attr("data-ratio")));
557
+ return {
558
+ ...height ? { height } : {},
559
+ ...width ? { width } : {}
560
+ };
561
+ }
562
+ function readStyleDimension(style, name) {
563
+ const escaped = escapeRegExp(name);
564
+ return readPositiveNumber(style.match(new RegExp(`(?:^|;)\\s*${escaped}\\s*:\\s*([^;]+)`, "i"))?.[1]);
565
+ }
566
+ function deriveHeightFromRatio(width, ratio) {
567
+ if (!width || !ratio) return void 0;
568
+ return Math.round(width * ratio);
569
+ }
570
+ function isPlaceholderImageSrc(value) {
571
+ const normalized = value.trim().toLowerCase();
572
+ return !normalized || normalized === "about:blank" || normalized.startsWith("data:") || normalized.startsWith("blob:") || normalized.startsWith("javascript:");
573
+ }
574
+ function sanitizeAnchors($, content) {
575
+ content.find("a").each((_, element) => {
576
+ const anchor = $(element);
577
+ const label = normalizeText(anchor.text());
578
+ const href = normalizeWechatHref(anchor.attr("href"));
579
+ if (!href) {
580
+ anchor.replaceWith(escapeHtmlText2(label));
581
+ return;
582
+ }
583
+ for (const key of Object.keys(anchor.attr() ?? {})) {
584
+ anchor.removeAttr(key);
585
+ }
586
+ anchor.attr("href", href);
587
+ anchor.text(label || href);
588
+ });
589
+ }
590
+ function sanitizeEncodedAnchors(html) {
591
+ if (!html || !html.includes("&lt;a")) return html;
592
+ return html.replace(ENCODED_ANCHOR_RE, (encodedAnchor) => {
593
+ const decoded = decodeHtmlEntities(encodedAnchor);
594
+ const $ = cheerio.load(decoded);
595
+ const anchor = $("a").first();
596
+ if (!anchor.length) return encodedAnchor;
597
+ const label = normalizeText(anchor.text());
598
+ const href = normalizeWechatHref(anchor.attr("href"));
599
+ if (!href) return escapeHtmlText2(label);
600
+ return `<a href="${escapeHtmlAttribute(href)}">${escapeHtmlText2(label || href)}</a>`;
601
+ });
602
+ }
603
+ function removeNoise(content) {
604
+ content.find(
605
+ [
606
+ ".qr_code_pc",
607
+ ".reward_area",
608
+ ".rich_media_tool",
609
+ ".rich_media_meta_list",
610
+ "#js_pc_qr_code",
611
+ "mp-common-profile",
612
+ "script",
613
+ "style"
614
+ ].join(",")
615
+ ).remove();
616
+ }
617
+ function extractCodeBlocks($, content) {
618
+ const codeBlocks = [];
619
+ content.find(".code-snippet__fix").each((_, element) => {
620
+ const snippet = $(element);
621
+ snippet.find(".code-snippet__line-index").remove();
622
+ const pre = snippet.find("pre").first();
623
+ const lang = readCodeLanguage(pre) || readCodeLanguage(snippet);
624
+ const lines = snippet.find("code").toArray().map((code) => readCodeNodeText($, $(code))).filter((line) => line && !/^[ce]?ounter\(line/.test(line.trim()));
625
+ pushCodeBlock(snippet, codeBlocks, {
626
+ code: lines.length ? lines.join("\n") : readCodeNodeText($, snippet),
627
+ lang
628
+ });
629
+ });
630
+ content.find("pre").each((_, element) => {
631
+ const pre = $(element);
632
+ if (pre.closest(".code-snippet__fix").length) return;
633
+ const lineCodes = pre.children("code").toArray();
634
+ const code = lineCodes.length > 1 ? lineCodes.map((line) => readCodeNodeText($, $(line))).filter(Boolean).join("\n") : readCodeNodeText($, pre);
635
+ pushCodeBlock(pre, codeBlocks, {
636
+ code,
637
+ lang: readCodeLanguage(pre) || readCodeLanguage(pre.find("code").first())
638
+ });
639
+ });
640
+ content.find("code").each((_, element) => {
641
+ const code = $(element);
642
+ if (code.closest("pre, .code-snippet__fix").length) return;
643
+ if (!code.find("br").length) return;
644
+ const parent = code.parent();
645
+ const elementSiblings = parent.children().toArray().filter((child) => child.type === "tag");
646
+ if (elementSiblings.length !== 1) return;
647
+ const parentTag = String(parent.prop("tagName") ?? "").toLowerCase();
648
+ const target = parentTag === "section" || parentTag === "div" || parentTag === "p" ? parent : code;
649
+ pushCodeBlock(target, codeBlocks, {
650
+ code: readCodeNodeText($, code),
651
+ lang: readCodeLanguage(code)
652
+ });
653
+ });
654
+ return codeBlocks;
655
+ }
656
+ function pushCodeBlock(node, codeBlocks, block) {
657
+ const code = block.code.replace(/\n{3,}/g, "\n\n").trimEnd();
658
+ if (!code) {
659
+ node.remove();
660
+ return;
661
+ }
662
+ const placeholder = `CODEBLOCK-PLACEHOLDER-${codeBlocks.length}`;
663
+ codeBlocks.push({ code, lang: block.lang });
664
+ node.replaceWith(`<p>${placeholder}</p>`);
665
+ }
666
+ function readCodeLanguage(node) {
667
+ if (!node.length) return "";
668
+ const dataLang = normalizeCodeLanguage(node.attr("data-lang") ?? "");
669
+ if (dataLang) return dataLang;
670
+ const className = node.attr("class") ?? "";
671
+ return normalizeCodeLanguage(className.match(/(?:^|\s)(?:language|lang)-([a-zA-Z0-9#+.-]+)/)?.[1] ?? "");
672
+ }
673
+ function readCodeNodeText($, node) {
674
+ return decodeHtmlEntities(restoreNbspFlattenedCodeLines(collectCodeNodeText($, node))).replace(/\u00a0/g, " ").replace(/\r\n/g, "\n").replace(/\r/g, "\n").replace(/[ \t]+\n/g, "\n").trimEnd();
675
+ }
676
+ function restoreNbspFlattenedCodeLines(text) {
677
+ if (!text || text.includes("\n") || !text.includes("\xA0")) return text;
678
+ const runs = text.match(/ ?(?:\u00a0 ?)+/g) ?? [];
679
+ if (runs.length < 2) return text;
680
+ let restored = text.replace(/ ?(?:\u00a0 ?)+/g, (match) => {
681
+ const nbspCount = [...match].filter((char) => char === "\xA0").length;
682
+ const indent = nbspCount <= 1 ? 0 : nbspCount * 2;
683
+ return `
684
+ ${" ".repeat(indent)}`;
685
+ });
686
+ restored = restored.replace(/,[ \t]+(\)[ \t]*\{)/g, ",\n$1").replace(/([;}])[ \t]+(?=\})/g, "$1\n");
687
+ return restored;
688
+ }
689
+ function collectCodeNodeText($, node) {
690
+ let output = "";
691
+ const children = node.contents().toArray();
692
+ const hasElementChildren = children.some((child) => child.type === "tag");
693
+ for (const child of children) {
694
+ if (child.type === "text") {
695
+ const text = child.data ?? "";
696
+ if (hasElementChildren && !text.trim() && !isInlineTokenGap(child, text)) continue;
697
+ output += text;
698
+ continue;
699
+ }
700
+ if (child.type !== "tag") continue;
701
+ const tag = String(child.tagName ?? "").toLowerCase();
702
+ if (tag === "br") {
703
+ output += "\n";
704
+ continue;
705
+ }
706
+ output += collectCodeNodeText($, $(child));
707
+ }
708
+ return output;
709
+ }
710
+ function extractLegacySwiperHtml($, html) {
711
+ const container = $("#js_image_content").first();
712
+ const parts = [];
713
+ const title = container.find(".rich_media_title").first();
714
+ const description = container.find("#js_image_desc").first();
715
+ if (title.length) {
716
+ transformInlineBreaks($, title);
717
+ parts.push($.html(title));
718
+ }
719
+ if (description.length) {
720
+ transformInlineBreaks($, description);
721
+ parts.push($.html(description));
722
+ }
723
+ const existing = parts.join("\n");
724
+ const additionalImages = collectLegacySwiperImages(html).filter((url) => !existing.includes(url)).map((url) => `<p><img src="${escapeHtmlAttribute(url)}"></p>`);
725
+ return [...parts, ...additionalImages].join("\n\n").trim();
726
+ }
727
+ function collectLegacySwiperImages(html) {
728
+ const $ = cheerio.load(html);
729
+ const seen = /* @__PURE__ */ new Set();
730
+ const urls = [];
731
+ $(".swiper_item_img img").each((_, element) => {
732
+ const url = toWechatOriginalImageUrl(normalizeWechatImageUrl(readPreferredImageSource($(element))));
733
+ if (!url || seen.has(url)) return;
734
+ seen.add(url);
735
+ urls.push(url);
736
+ });
737
+ return urls;
738
+ }
739
+ function buildWechatImageShareHtml(data) {
740
+ const imagesHtml = data.pictures.map((picture) => {
741
+ const width = picture.width ? ` width="${picture.width}"` : "";
742
+ const height = picture.height ? ` height="${picture.height}"` : "";
743
+ return `<p><img src="${escapeHtmlAttribute(picture.src)}"${width}${height}></p>`;
744
+ }).join("\n\n");
745
+ const textHtml = buildParagraphHtml(data.description);
746
+ return [imagesHtml, textHtml].filter(Boolean).join("\n\n");
747
+ }
748
+ function buildParagraphHtml(text) {
749
+ return text.replace(/\r/g, "").split(/\n{2,}/).map((paragraph) => paragraph.trim()).filter(Boolean).map((paragraph) => `<p>${escapeHtmlText2(paragraph).replace(/\n/g, "<br>")}</p>`).join("\n");
750
+ }
751
+ function extractWechatImageShareData(html, metaTitle) {
752
+ const publishTime = formatWechatTimestamp(
753
+ extractWechatJsNumber(html, "ori_create_time") ?? extractWechatJsNumber(html, "ct")
754
+ );
755
+ return {
756
+ author: extractWechatJsString(html, "nick_name") || extractWechatJsString(html, "nickname"),
757
+ description: extractWechatJsString(html, "content_noencode") || extractWechatJsString(html, "desc"),
758
+ itemShowType: extractWechatJsString(html, "item_show_type"),
759
+ pictures: extractWechatPicturePageItems(html),
760
+ publishTime,
761
+ realItemShowType: extractWechatJsString(html, "real_item_show_type"),
762
+ title: metaTitle || extractWechatJsString(html, "msg_title") || extractWechatJsString(html, "title")
763
+ };
764
+ }
765
+ function isWechatImageShareType(data) {
766
+ return data.itemShowType === "8" || data.realItemShowType === "8";
767
+ }
768
+ function extractWechatPicturePageItems(html) {
769
+ const arrayBody = extractAssignedArrayBody(html, "picture_page_info_list");
770
+ if (!arrayBody) return [];
771
+ const seen = /* @__PURE__ */ new Set();
772
+ const pictures = [];
773
+ for (const objectSource of splitTopLevelObjects(arrayBody)) {
774
+ const src = toWechatOriginalImageUrl(normalizeWechatImageUrl(extractTopLevelStringField(objectSource, "cdn_url")));
775
+ const width = parseWechatNumericField(extractTopLevelStringField(objectSource, "width"));
776
+ const height = parseWechatNumericField(extractTopLevelStringField(objectSource, "height"));
777
+ if (!src || seen.has(src)) continue;
778
+ if (isDecorativeEmojiImage({ height, src, width })) continue;
779
+ seen.add(src);
780
+ const picture = { src };
781
+ if (width) picture.width = width;
782
+ if (height) picture.height = height;
783
+ pictures.push(picture);
784
+ }
785
+ return pictures;
786
+ }
787
+ function extractAssignedArrayBody(html, variableName) {
788
+ const field = escapeRegExp(variableName);
789
+ const patterns = [
790
+ new RegExp(`\\b${field}\\s*:\\s*\\[`, "g"),
791
+ new RegExp(`window\\.${field}\\s*=`, "g")
792
+ ];
793
+ for (const pattern of patterns) {
794
+ let match;
795
+ while ((match = pattern.exec(html)) !== null) {
796
+ const fromEquals = match[0].endsWith("[") ? match.index + match[0].length - 1 : match.index + match[0].length;
797
+ let searchFrom = fromEquals;
798
+ while (searchFrom < html.length) {
799
+ const arrayStart = html.indexOf("[", searchFrom);
800
+ if (arrayStart < 0) break;
801
+ const body = extractArrayLiteralBody(html, arrayStart);
802
+ if (body.trim()) return body;
803
+ searchFrom = arrayStart + 1;
804
+ }
805
+ }
806
+ }
807
+ return "";
808
+ }
809
+ function extractArrayLiteralBody(html, arrayStart) {
810
+ let depth = 0;
811
+ let quote = "";
812
+ let escaped = false;
813
+ for (let index = arrayStart; index < html.length; index += 1) {
814
+ const char = html[index];
815
+ if (quote) {
816
+ if (escaped) escaped = false;
817
+ else if (char === "\\") escaped = true;
818
+ else if (char === quote) quote = "";
819
+ continue;
820
+ }
821
+ if (char === '"' || char === "'") {
822
+ quote = char;
823
+ continue;
824
+ }
825
+ if (char === "[") depth += 1;
826
+ if (char === "]") {
827
+ depth -= 1;
828
+ if (depth === 0) return html.slice(arrayStart + 1, index);
829
+ }
830
+ }
831
+ return "";
832
+ }
833
+ function splitTopLevelObjects(arrayBody) {
834
+ const objects = [];
835
+ let depth = 0;
836
+ let start = -1;
837
+ let quote = "";
838
+ let escaped = false;
839
+ for (let index = 0; index < arrayBody.length; index += 1) {
840
+ const char = arrayBody[index];
841
+ if (quote) {
842
+ if (escaped) escaped = false;
843
+ else if (char === "\\") escaped = true;
844
+ else if (char === quote) quote = "";
845
+ continue;
846
+ }
847
+ if (char === '"' || char === "'") {
848
+ quote = char;
849
+ continue;
850
+ }
851
+ if (char === "{") {
852
+ if (depth === 0) start = index;
853
+ depth += 1;
854
+ continue;
855
+ }
856
+ if (char === "}") {
857
+ depth -= 1;
858
+ if (depth === 0 && start >= 0) {
859
+ objects.push(arrayBody.slice(start, index + 1));
860
+ start = -1;
861
+ }
862
+ }
863
+ }
864
+ return objects;
865
+ }
866
+ function extractTopLevelStringField(objectSource, fieldName) {
867
+ const fieldPattern = new RegExp(`\\b${escapeRegExp(fieldName)}\\b\\s*:\\s*(['"])`, "g");
868
+ let match;
869
+ while ((match = fieldPattern.exec(objectSource)) !== null) {
870
+ if (objectDepthAt(objectSource, match.index) !== 1) continue;
871
+ const quoted = extractQuotedValue(objectSource, fieldPattern.lastIndex - 1);
872
+ if (!quoted) continue;
873
+ const decoded = decodeWechatJsString(quoted);
874
+ if (decoded) return decoded;
875
+ }
876
+ return "";
877
+ }
878
+ function objectDepthAt(source, targetIndex) {
879
+ let depth = 0;
880
+ let quote = "";
881
+ let escaped = false;
882
+ for (let index = 0; index < targetIndex; index += 1) {
883
+ const char = source[index];
884
+ if (quote) {
885
+ if (escaped) escaped = false;
886
+ else if (char === "\\") escaped = true;
887
+ else if (char === quote) quote = "";
888
+ continue;
889
+ }
890
+ if (char === '"' || char === "'") quote = char;
891
+ else if (char === "{") depth += 1;
892
+ else if (char === "}") depth -= 1;
893
+ }
894
+ return depth;
895
+ }
896
+ function extractWechatJsString(html, fieldName) {
897
+ const field = escapeRegExp(fieldName);
898
+ const patterns = [
899
+ new RegExp(`\\b${field}\\s*:\\s*(['"])`, "g"),
900
+ new RegExp(`window\\.${field}\\s*=\\s*(?:window\\.[A-Za-z_$][\\w$]*\\s*=\\s*)?(['"])`, "g"),
901
+ new RegExp(`var\\s+${field}\\s*=\\s*(['"])`, "g")
902
+ ];
903
+ for (const pattern of patterns) {
904
+ const match = pattern.exec(html);
905
+ if (!match) continue;
906
+ const quoted = extractQuotedValue(html, pattern.lastIndex - 1);
907
+ if (!quoted) continue;
908
+ const decoded = decodeWechatJsString(quoted);
909
+ if (decoded) return decoded;
910
+ }
911
+ return "";
912
+ }
913
+ function extractQuotedValue(source, quoteIndex) {
914
+ const quote = source[quoteIndex];
915
+ if (quote !== "'" && quote !== '"') return "";
916
+ let value = "";
917
+ let escaped = false;
918
+ for (let index = quoteIndex + 1; index < source.length; index += 1) {
919
+ const char = source[index];
920
+ if (escaped) {
921
+ value += `\\${char}`;
922
+ escaped = false;
923
+ continue;
924
+ }
925
+ if (char === "\\") {
926
+ escaped = true;
927
+ continue;
928
+ }
929
+ if (char === quote) return value;
930
+ value += char;
931
+ }
932
+ return "";
933
+ }
934
+ function decodeWechatJsString(value) {
935
+ return decodeHtmlEntities(
936
+ value.replace(/\\x([0-9a-fA-F]{2})/g, (match, hex) => decodeCodePoint(match, Number.parseInt(hex, 16))).replace(/\\u\{([0-9a-fA-F]+)\}/g, (match, hex) => decodeCodePoint(match, Number.parseInt(hex, 16))).replace(/\\u([0-9a-fA-F]{4})/g, (match, hex) => decodeCodePoint(match, Number.parseInt(hex, 16))).replace(/\\\//g, "/").replace(/\\n/g, "\n").replace(/\\r/g, "\r").replace(/\\t/g, " ").replace(/\\b/g, "\b").replace(/\\f/g, "\f").replace(/\\'/g, "'").replace(/\\"/g, '"').replace(/\\\\/g, "\\")
937
+ ).replace(/&nbsp;/g, " ").trim();
938
+ }
939
+ function decodeCodePoint(fallback, value) {
940
+ return Number.isFinite(value) ? String.fromCodePoint(value) : fallback;
941
+ }
942
+ function extractWechatJsNumber(html, fieldName) {
943
+ const value = Number(extractWechatJsString(html, fieldName));
944
+ return Number.isFinite(value) ? value : null;
945
+ }
946
+ function parseWechatNumericField(value) {
947
+ const parsed = Number(value);
948
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : void 0;
949
+ }
950
+ function readPositiveNumber(value) {
951
+ const matched = String(value ?? "").match(/(\d+(?:\.\d+)?)/)?.[1];
952
+ const parsed = Number(matched);
953
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : void 0;
954
+ }
955
+ function formatWechatTimestamp(value) {
956
+ if (!value || !Number.isFinite(value) || value <= 0) return "";
957
+ const seconds = value > 1e10 ? Math.floor(value / 1e3) : value;
958
+ const date = new Date((seconds + 8 * 60 * 60) * 1e3);
959
+ return date.toISOString().slice(0, 19).replace("T", " ");
960
+ }
961
+ function transformInlineBreaks($, node) {
962
+ const tag = String(node.prop("tagName") ?? "").toLowerCase();
963
+ if (tag === "code" || tag === "pre") return;
964
+ const elementChildren = node.children().toArray().filter((child) => child.type === "tag");
965
+ if (elementChildren.length === 0) {
966
+ const rawText = node.text().replace(/\r/g, "");
967
+ if (rawText.includes("\n")) {
968
+ const lines = rawText.split(/\n+/).map((line) => line.trim()).filter(Boolean);
969
+ node.html(lines.map(escapeHtmlText2).join("<br>"));
970
+ }
971
+ return;
972
+ }
973
+ for (const child of elementChildren) {
974
+ transformInlineBreaks($, $(child));
975
+ }
976
+ }
977
+ function collectImageUrls(html) {
978
+ const $ = cheerio.load(html);
979
+ const seen = /* @__PURE__ */ new Set();
980
+ const urls = [];
981
+ $("img[src]").each((_, element) => {
982
+ const src = normalizeWechatImageUrl($(element).attr("src") ?? "");
983
+ if (!src || seen.has(src)) return;
984
+ seen.add(src);
985
+ urls.push(src);
986
+ });
987
+ return urls;
988
+ }
989
+ function readMeta($, key) {
990
+ return normalizeText($(`meta[property="${key}"], meta[name="${key}"]`).first().attr("content") ?? "");
991
+ }
992
+ function normalizeWechatHref(value) {
993
+ const href = decodeHtmlEntities(value ?? "").trim();
994
+ return normalizeWechatUrl(href);
995
+ }
996
+ function normalizeWechatImageUrl(value) {
997
+ const url = normalizeWechatUrl(value);
998
+ if (!url) return "";
999
+ return url.replace(/#imgIndex=\d+$/i, "").replace(/#$/, "");
1000
+ }
1001
+ function normalizeWechatUrl(value) {
1002
+ const trimmed = decodeWechatJsString(String(value ?? "")).trim();
1003
+ if (!trimmed || isPlaceholderImageSrc(trimmed)) return "";
1004
+ if (/^https?:\/\//i.test(trimmed)) return trimmed.replace(/^http:\/\//i, "https://");
1005
+ if (trimmed.startsWith("//")) return `https:${trimmed}`;
1006
+ return "";
1007
+ }
1008
+ function toWechatOriginalImageUrl(url) {
1009
+ if (!/^https:\/\/[^/]*qpic\.cn\//i.test(url)) return url;
1010
+ return url.replace(/\/\d{2,4}(?=\?|$)/, "/0");
1011
+ }
1012
+ function normalizeTitle(value) {
1013
+ return normalizeText(value).replace(/\s*[-_]\s*微信公众平台\s*$/i, "").replace(/\s*[-_]\s*微信公众号\s*$/i, "").trim();
1014
+ }
1015
+ function normalizeCodeLanguage(value) {
1016
+ return value.trim().replace(/[^\w#+.-]/g, "");
1017
+ }
1018
+ function normalizeText(value) {
1019
+ return decodeHtmlEntities(value).replace(/\s+/g, " ").trim();
1020
+ }
1021
+ function decodeHtmlEntities(value) {
1022
+ let previous = "";
1023
+ let current = value;
1024
+ while (previous !== current) {
1025
+ previous = current;
1026
+ current = current.replace(/&amp;/gi, "&").replace(/&quot;/gi, '"').replace(/&#39;/gi, "'").replace(/&lt;/gi, "<").replace(/&gt;/gi, ">").replace(/&#(\d+);/g, (_, code) => String.fromCodePoint(Number.parseInt(code, 10))).replace(/&#x([0-9a-f]+);/gi, (_, code) => String.fromCodePoint(Number.parseInt(code, 16)));
1027
+ }
1028
+ return current;
1029
+ }
1030
+ function escapeHtmlText2(value) {
1031
+ return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
1032
+ }
1033
+ function escapeHtmlAttribute(value) {
1034
+ return escapeHtmlText2(value).replace(/"/g, "&quot;").replace(/'/g, "&#39;");
1035
+ }
1036
+ function escapeRegExp(value) {
1037
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1038
+ }
1039
+ function isWechatContentExpired(html) {
1040
+ if (!html || !html.includes("weui-msg") && !html.includes("weui_msg")) return false;
1041
+ return EXPIRED_PATTERNS.some((pattern) => html.includes(pattern));
1042
+ }
1043
+ function isInlineTokenGap(node, text) {
1044
+ if (/[\r\n]/.test(text)) return false;
1045
+ return isCodeToken(node.prev) && isCodeToken(node.next);
1046
+ }
1047
+ function isCodeToken(node) {
1048
+ if (node?.type !== "tag" || String(node.name ?? "").toLowerCase() === "br") return false;
1049
+ return hasCodeText(node);
1050
+ }
1051
+ function hasCodeText(node) {
1052
+ if (node.type === "text") return Boolean(node.data?.trim());
1053
+ return (node.children ?? []).some(hasCodeText);
1054
+ }
1055
+
1056
+ // ../../packages/clip-engine/src/wechatArticleToMarkdown/guard.ts
1057
+ var provider = null;
1058
+ function currentWechatCaptureGuard() {
1059
+ return provider ? provider() : null;
1060
+ }
1061
+
1062
+ // ../../packages/clip-engine/src/wechatArticleToMarkdown/capture.ts
1063
+ var DEFAULT_TIMEOUT_MS2 = 3e4;
1064
+ var DEFAULT_SELECTOR_TIMEOUT_MS = 1e4;
1065
+ var DEFAULT_SETTLE_MS = 2e3;
1066
+ var DEFAULT_HEADERS = {
1067
+ Accept: "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
1068
+ "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
1069
+ "Cache-Control": "no-cache",
1070
+ Pragma: "no-cache",
1071
+ Referer: "https://mp.weixin.qq.com/"
1072
+ };
1073
+ async function captureWechatArticleHtml(rawUrl, options = {}) {
1074
+ const url = assertWechatArticleUrl(rawUrl);
1075
+ const guard = currentWechatCaptureGuard();
1076
+ const canonical = canonicalWechatUrl(url);
1077
+ const cacheable = guard !== null && !options.headers && !options.launchOptions;
1078
+ const cached = guard && cacheable && options.cache !== "bypass" ? guard.cached(canonical) : void 0;
1079
+ if (cached) return { ...JSON.parse(cached), replayable: true, url };
1080
+ const token = guard?.acquireFetch();
1081
+ let outcome = "failure";
1082
+ let reason = "";
1083
+ let browser = null;
1084
+ let context = null;
1085
+ let expired = false;
1086
+ const watchdog = setTimeout(() => {
1087
+ expired = true;
1088
+ void browser?.close().catch(() => void 0);
1089
+ }, 12e4);
1090
+ try {
1091
+ browser = await launchBrowser(options.launchOptions);
1092
+ if (expired) throw new Error("WeChat capture hard deadline exceeded");
1093
+ context = await browser.newContext({
1094
+ extraHTTPHeaders: {
1095
+ ...DEFAULT_HEADERS,
1096
+ ...options.headers ?? {}
1097
+ },
1098
+ locale: "zh-CN",
1099
+ viewport: { width: 1365, height: 900 }
1100
+ });
1101
+ const page = await context.newPage();
1102
+ const response = await page.goto(url, {
1103
+ timeout: Math.min(options.timeoutMs ?? DEFAULT_TIMEOUT_MS2, 9e4),
1104
+ waitUntil: options.waitUntil ?? "domcontentloaded"
1105
+ });
1106
+ if ([401, 403, 429].includes(response?.status() ?? 0)) {
1107
+ outcome = "blocked";
1108
+ throw new WechatArticleToMarkdownError("CAPTURE_BLOCKED", `capture blocked: HTTP ${response?.status()}`, { url });
1109
+ }
1110
+ const selectorFound = await waitForArticleContent(page, options.selectorTimeoutMs ?? DEFAULT_SELECTOR_TIMEOUT_MS);
1111
+ const settleMs = options.settleMs ?? DEFAULT_SETTLE_MS;
1112
+ if (settleMs > 0) await page.waitForTimeout(settleMs);
1113
+ const html = await page.content();
1114
+ const title = await page.title().catch(() => "");
1115
+ const finalUrl = page.url();
1116
+ const contentStillPresent = await pageHasArticleContent(page).catch(() => false);
1117
+ const block = detectCaptureBlock({ html, title, url: finalUrl });
1118
+ if (block.blocked) {
1119
+ outcome = "blocked";
1120
+ const reason2 = block.reason ?? "unknown";
1121
+ const code = wechatErrorCodeForCaptureBlockReason(block.reason);
1122
+ throw new WechatArticleToMarkdownError(code, `capture blocked: ${reason2}`, {
1123
+ reason: reason2,
1124
+ url
1125
+ });
1126
+ }
1127
+ if (!selectorFound || !contentStillPresent)
1128
+ throw new WechatArticleToMarkdownError(
1129
+ "CAPTURE_FAILED",
1130
+ `WeChat article content missing (not a successful circuit probe; finalUrl=${finalUrl.slice(0, 200)}; title=${title.slice(0, 80)})`,
1131
+ { url }
1132
+ );
1133
+ const captured = {
1134
+ capturedAt: (/* @__PURE__ */ new Date()).toISOString(),
1135
+ finalUrl,
1136
+ html,
1137
+ selectorFound: selectorFound && contentStillPresent,
1138
+ title,
1139
+ url
1140
+ };
1141
+ const parsed = parseWechatArticleHtml(html, { sourceUrl: finalUrl || url });
1142
+ if (!parsed.contentHtml.replace(/<[^>]*>/g, "").replace(/&nbsp;|\s/g, "") && !/<(?:img|video|iframe)\b/i.test(parsed.contentHtml))
1143
+ throw new WechatArticleToMarkdownError("CONTENT_NOT_FOUND", "WeChat article has no meaningful content", { url });
1144
+ outcome = "success";
1145
+ return { ...captured, replayable: guard !== null && cacheable && cacheCapture(guard, canonical, captured) };
1146
+ } catch (error) {
1147
+ reason = errorMessage(error);
1148
+ if (error instanceof WechatArticleToMarkdownError) throw error;
1149
+ throw new WechatArticleToMarkdownError("CAPTURE_FAILED", errorMessage(error), { url });
1150
+ } finally {
1151
+ await context?.close().catch(() => void 0);
1152
+ await browser?.close().catch(() => void 0);
1153
+ clearTimeout(watchdog);
1154
+ if (guard && token !== void 0) guard.finishFetch(token, outcome, reason);
1155
+ }
1156
+ }
1157
+ function articleContentProbe() {
1158
+ const win = globalThis;
1159
+ return Boolean(
1160
+ win.document?.querySelector("#js_content, #js_image_content, .swiper_item_img") || win.item_show_type === "8" || Array.isArray(win.picture_page_info_list) && win.picture_page_info_list.length > 0
1161
+ );
1162
+ }
1163
+ var ARTICLE_CONTENT_PROBE = articleContentProbe;
1164
+ async function waitForArticleContent(page, timeoutMs) {
1165
+ try {
1166
+ await page.waitForFunction(ARTICLE_CONTENT_PROBE, { timeout: timeoutMs });
1167
+ return true;
1168
+ } catch {
1169
+ return false;
1170
+ }
1171
+ }
1172
+ async function pageHasArticleContent(page) {
1173
+ return Boolean(await page.evaluate(ARTICLE_CONTENT_PROBE));
1174
+ }
1175
+ function cacheCapture(guard, canonical, captured) {
1176
+ try {
1177
+ const stored = guard.cache(canonical, JSON.stringify(captured));
1178
+ if (!stored) logWarn("wechat-article.capture", "cache.skipped.oversize", { canonical, htmlBytes: Buffer.byteLength(captured.html) });
1179
+ return stored;
1180
+ } catch (error) {
1181
+ logWarn("wechat-article.capture", "cache.write.failed", { canonical, error: errorMessage(error) });
1182
+ return false;
1183
+ }
1184
+ }
1185
+ function errorMessage(error) {
1186
+ return error instanceof Error ? error.message : String(error);
1187
+ }
1188
+
1189
+ // ../../packages/clip-engine/src/wechatArticleToMarkdown/markdown.ts
1190
+ import TurndownService from "turndown";
1191
+ import { gfm } from "turndown-plugin-gfm";
1192
+ function convertWechatContentHtmlToMarkdown(contentHtml, codeBlocks = []) {
1193
+ const service = new TurndownService({
1194
+ bulletListMarker: "-",
1195
+ codeBlockStyle: "fenced",
1196
+ emDelimiter: "*",
1197
+ headingStyle: "atx"
1198
+ });
1199
+ service.use(gfm);
1200
+ useFlatInlineFormatting(service);
1201
+ const { html, tables } = extractHtmlTablesToMarkdown(contentHtml, service);
1202
+ let markdown = service.turndown(html);
1203
+ for (const [index, block] of codeBlocks.entries()) {
1204
+ markdown = markdown.replace(`CODEBLOCK-PLACEHOLDER-${index}`, formatCodeBlock(block));
1205
+ }
1206
+ markdown = restoreTablePlaceholders(markdown, tables);
1207
+ return markdown.replace(/\u00a0/g, " ").replace(/\n{4,}/g, "\n\n\n").replace(/[ \t]+$/gm, "").trim();
1208
+ }
1209
+ function replaceWechatMarkdownImageUrls(markdown, urlMap) {
1210
+ return replaceRemoteMarkdownImageUrls(markdown, urlMap);
1211
+ }
1212
+ function buildWechatArticleMarkdown(metadata, bodyMarkdown) {
1213
+ const lines = [`# ${metadata.title}`, ""];
1214
+ if (metadata.author) lines.push(`> \u516C\u4F17\u53F7: ${metadata.author}`);
1215
+ if (metadata.publishTime) lines.push(`> \u53D1\u5E03\u65F6\u95F4: ${metadata.publishTime}`);
1216
+ if (metadata.sourceUrl) lines.push(`> \u539F\u6587\u94FE\u63A5: ${metadata.sourceUrl}`);
1217
+ if (metadata.author || metadata.publishTime || metadata.sourceUrl) lines.push("");
1218
+ lines.push("---", "");
1219
+ return `${lines.join("\n")}${bodyMarkdown.trim()}
1220
+ `;
1221
+ }
1222
+ function formatCodeBlock(block) {
1223
+ const fence = longestBacktickFence(block.code);
1224
+ return `
1225
+ ${fence}${block.lang}
1226
+ ${block.code.trimEnd()}
1227
+ ${fence}
1228
+ `;
1229
+ }
1230
+ function longestBacktickFence(code) {
1231
+ const longest = Math.max(2, ...Array.from(code.matchAll(/`+/g), (match) => match[0]?.length ?? 0));
1232
+ return "`".repeat(longest + 1);
1233
+ }
1234
+
1235
+ // ../../packages/clip-engine/src/wechatArticleToMarkdown/normalize.ts
1236
+ var METADATA_LABELS = /* @__PURE__ */ new Set([
1237
+ "\u4F5C\u8005",
1238
+ "\u516C\u4F17\u53F7",
1239
+ "\u53D1\u5E03\u65F6\u95F4",
1240
+ "\u53D1\u5E03\u65E5\u671F",
1241
+ "\u539F\u6587",
1242
+ "\u539F\u6587\u94FE\u63A5",
1243
+ "\u94FE\u63A5",
1244
+ "source",
1245
+ "sourceurl"
1246
+ ]);
1247
+ function normalizeWechatArticleMarkdown(markdown, metadata) {
1248
+ const content = stripLeadingWechatMetadata(normalizeLineEndings(markdown));
1249
+ const withoutReference = stripTrailingMetadataBlock(content);
1250
+ const cleaned = stripClipBoilerplate(stripWechatVideoPlayerChrome(withoutReference), "wechat").markdown;
1251
+ const body = stripLeadingDuplicateTitleHeading(
1252
+ // Decoration clean-up can unwrap bold-wrapped image lines ("**![](a)**")
1253
+ // that kept a section-wide bold run from being repaired; normalize again
1254
+ // (idempotent) so the exposed run is closed like any other.
1255
+ normalizeClipMarkdownBody(cleanWechatDecorations(normalizeClipMarkdownBody(cleaned))).trim(),
1256
+ metadata.title
1257
+ ).trim();
1258
+ const footer = formatClipFooter({
1259
+ site: "WeChat",
1260
+ sourceUrl: extractHttpUrl(metadata.sourceUrl),
1261
+ author: metadata.author,
1262
+ publishTime: metadata.publishTime
1263
+ });
1264
+ return [body, footer].filter(Boolean).join("\n\n");
1265
+ }
1266
+ function stripLeadingWechatMetadata(markdown) {
1267
+ const lines = markdown.split("\n");
1268
+ let index = skipBlankLines(lines, 0);
1269
+ if (isHeadingLine(lines[index])) {
1270
+ index += 1;
1271
+ index = skipBlankLines(lines, index);
1272
+ }
1273
+ while (index < lines.length) {
1274
+ const next = stripOneMetadataBlock(lines, index);
1275
+ if (next === index) break;
1276
+ index = skipBlankLines(lines, next);
1277
+ }
1278
+ if (isHorizontalRule(lines[index])) {
1279
+ index += 1;
1280
+ }
1281
+ return lines.slice(index).join("\n").trim();
1282
+ }
1283
+ function stripOneMetadataBlock(lines, startIndex) {
1284
+ const line = lines[startIndex];
1285
+ if (!line) return startIndex;
1286
+ if (isMetadataLine(line)) return startIndex + 1;
1287
+ if (!line.trim().startsWith(">")) return startIndex;
1288
+ let index = startIndex;
1289
+ let hasMetadata = false;
1290
+ while (index < lines.length && (lines[index]?.trim().startsWith(">") || lines[index]?.trim() === "")) {
1291
+ const current = lines[index] ?? "";
1292
+ if (current.trim() && !isMetadataLine(current)) break;
1293
+ if (isMetadataLine(current)) hasMetadata = true;
1294
+ index += 1;
1295
+ }
1296
+ return hasMetadata ? index : startIndex;
1297
+ }
1298
+ function stripTrailingMetadataBlock(markdown) {
1299
+ const lines = markdown.trim().split("\n");
1300
+ const end = skipTrailingBlankLines(lines, lines.length - 1);
1301
+ if (end < 0) return "";
1302
+ let start = end;
1303
+ let hasSourceReference = false;
1304
+ while (start >= 0) {
1305
+ const line = lines[start]?.trim() ?? "";
1306
+ if (!line) {
1307
+ start -= 1;
1308
+ continue;
1309
+ }
1310
+ if (!isFooterMetadataLine(line)) break;
1311
+ if (isSourceReferenceLine(line)) hasSourceReference = true;
1312
+ start -= 1;
1313
+ }
1314
+ if (!hasSourceReference) return markdown.trim();
1315
+ let bodyEnd = skipTrailingBlankLines(lines, start);
1316
+ if (isHorizontalRule(lines[bodyEnd])) bodyEnd = skipTrailingBlankLines(lines, bodyEnd - 1);
1317
+ return lines.slice(0, bodyEnd + 1).join("\n").trim();
1318
+ }
1319
+ function isMetadataLine(line) {
1320
+ return Boolean(parseMetadataLine(line));
1321
+ }
1322
+ function parseMetadataLine(line) {
1323
+ const cleaned = line.trim().replace(/^>\s*/, "");
1324
+ const match = cleaned.match(/^([^::]{1,32})\s*[::]\s*(.+)$/);
1325
+ const label = normalizeLabel(match?.[1] ?? "");
1326
+ const value = match?.[2]?.trim() ?? "";
1327
+ if (!label || !value || !METADATA_LABELS.has(label)) return null;
1328
+ return { label, value };
1329
+ }
1330
+ function isSourceReferenceLine(line) {
1331
+ if (/^>\s*Source:\s*\[[^\]]*\]\(https?:\/\//.test(line.trim())) return true;
1332
+ const normalized = line.trim().replace(/^>\s*/, "");
1333
+ return /^(?:引用|来源|原文|原文链接)\s*[::]/.test(normalized);
1334
+ }
1335
+ function isFooterMetadataLine(line) {
1336
+ return isSourceReferenceLine(line) || isMetadataLine(line);
1337
+ }
1338
+ var MAX_LEADING_IMAGE_LINES = 3;
1339
+ function stripLeadingDuplicateTitleHeading(markdown, title) {
1340
+ if (!title?.trim()) return markdown;
1341
+ const lines = markdown.split("\n");
1342
+ let index = skipBlankLines(lines, 0);
1343
+ let imageLines = 0;
1344
+ let kickerLines = 0;
1345
+ for (; ; ) {
1346
+ if (imageLines < MAX_LEADING_IMAGE_LINES && isImageOnlyLine(lines[index])) imageLines += 1;
1347
+ else if (kickerLines < 1 && isKickerLine(lines[index])) kickerLines += 1;
1348
+ else break;
1349
+ index = skipBlankLines(lines, index + 1);
1350
+ }
1351
+ const line = lines[index];
1352
+ if (!line || !isHeadingLine(line)) return markdown;
1353
+ const headingText = line.trim().replace(/^#\s+/, "").trim();
1354
+ if (normalizeTitleKey(headingText) !== normalizeTitleKey(title)) return markdown;
1355
+ const rest = skipBlankLines(lines, index + 1);
1356
+ return [...lines.slice(0, index), ...lines.slice(rest)].join("\n").trim();
1357
+ }
1358
+ function isImageOnlyLine(line) {
1359
+ if (typeof line !== "string" || !line.trim()) return false;
1360
+ const rest = line.replace(/<!--[\s\S]*?-->/g, " ").replace(/\[!\[[^\]\n]*\]\([^)\s]+(?:\s+"[^"]*")?\)\]\([^)\s]+\)/g, " ").replace(/!\[[^\]\n]*\]\([^)\s]+(?:\s+"[^"]*")?\)/g, " ");
1361
+ return rest.trim() === "";
1362
+ }
1363
+ var MAX_KICKER_CHARS = 24;
1364
+ function isKickerLine(line) {
1365
+ const text = line?.trim();
1366
+ if (!text || Array.from(text).length > MAX_KICKER_CHARS) return false;
1367
+ if (/[[\]()<>`*_#|!]/.test(text) || /^(?:[-+>]|\d+[.)])\s/.test(text)) return false;
1368
+ return !/[。!?!?.…;;::,,、]$/.test(text);
1369
+ }
1370
+ function normalizeTitleKey(value) {
1371
+ return value.replace(/[\s*_`#]/g, "").toLowerCase();
1372
+ }
1373
+ function isHeadingLine(line) {
1374
+ return typeof line === "string" && /^#\s+\S/.test(line.trim());
1375
+ }
1376
+ function isHorizontalRule(line) {
1377
+ return typeof line === "string" && /^(?:-{3,}|\*{3,}|_{3,})$/.test(line.trim());
1378
+ }
1379
+ function skipBlankLines(lines, startIndex) {
1380
+ let index = startIndex;
1381
+ while (index < lines.length && lines[index]?.trim() === "") index += 1;
1382
+ return index;
1383
+ }
1384
+ function skipTrailingBlankLines(lines, startIndex) {
1385
+ let index = startIndex;
1386
+ while (index >= 0 && lines[index]?.trim() === "") index -= 1;
1387
+ return index;
1388
+ }
1389
+ function extractHttpUrl(value) {
1390
+ const normalized = value.trim();
1391
+ if (!normalized) return "";
1392
+ const markdownLink = normalized.match(/\]\((https?:\/\/[^)\s]+)\)/i);
1393
+ if (markdownLink?.[1]) return markdownLink[1];
1394
+ const angleLink = normalized.match(/^<\s*(https?:\/\/[^>\s]+)\s*>$/i);
1395
+ if (angleLink?.[1]) return angleLink[1];
1396
+ const plain = normalized.match(/https?:\/\/\S+/i)?.[0]?.replace(/[),,。;;]+$/g, "");
1397
+ return plain ?? "";
1398
+ }
1399
+ function normalizeLabel(value) {
1400
+ return value.trim().toLowerCase().replace(/\s+/g, "");
1401
+ }
1402
+ function normalizeLineEndings(value) {
1403
+ return value.replace(/\r\n?/g, "\n");
1404
+ }
1405
+ var VIDEO_CHROME_RE = /(^|\n)(?:已关注\n+)?(?:关注\n+)?重播 分享 赞\n[\s\S]{0,2500}?\n视频详情(\*\*|__)?[ \t]*(?=\n|$)/g;
1406
+ var VIDEO_CHROME_MARKERS = ["\u60A8\u7684\u6D4F\u89C8\u5668\u4E0D\u652F\u6301 video \u6807\u7B7E", "\u500D\u901F\u64AD\u653E\u4E2D", "\u5207\u6362\u5230\u6A2A\u5C4F\u6A21\u5F0F", "\u8FDB\u5EA6\u6761\uFF0C\u767E\u5206\u4E4B"];
1407
+ var VIDEO_CHROME_TAIL_RE = /(^|\n)[^\n]{1,40}已关注\n+分享点赞在看\n+已同步到看一看写下你的评论\n+视频详情(\*\*|__)?[ \t]*(?=\n|$)/g;
1408
+ function stripWechatVideoPlayerChrome(markdown) {
1409
+ const withoutTail = markdown.includes("\u5DF2\u540C\u6B65\u5230\u770B\u4E00\u770B\u5199\u4E0B\u4F60\u7684\u8BC4\u8BBA") && !markdown.includes("\u91CD\u64AD \u5206\u4EAB \u8D5E") ? markdown.replace(VIDEO_CHROME_TAIL_RE, (_block, lead, closer) => `${lead}${closer ? `
1410
+ ${closer}` : ""}`) : markdown;
1411
+ if (!withoutTail.includes("\u91CD\u64AD \u5206\u4EAB \u8D5E")) return withoutTail;
1412
+ return withoutTail.replace(VIDEO_CHROME_RE, (block, lead, closer) => {
1413
+ if (VIDEO_CHROME_MARKERS.filter((marker) => block.includes(marker)).length < 2) return block;
1414
+ const title = /\n继续观看\n+([^\n]+)\n/.exec(block)?.[1]?.trim();
1415
+ const note = title && title !== "\u89C2\u770B\u66F4\u591A" ? `> \u{1F3AC} \u89C6\u9891\uFF1A${title}\uFF08\u8BF7\u5728\u539F\u6587\u4E2D\u89C2\u770B\uFF09` : "> \u{1F3AC} \u89C6\u9891\uFF08\u8BF7\u5728\u539F\u6587\u4E2D\u89C2\u770B\uFF09";
1416
+ return `${lead}${note}${closer ? `
1417
+
1418
+ ${closer}` : ""}`;
1419
+ });
1420
+ }
1421
+ var IMAGE_UNIT = String.raw`!\[(?:\\.|[^\]\\\n])*\]\([^)\s]+(?:\s+"[^"]*")?\)(?:[ \t]*<!--[\s\S]*?-->)?`;
1422
+ var BOLD_WRAPPED_IMAGE_LINE_RE = new RegExp(String.raw`^([ \t]*)(?:\*\*|__)+[ \t]*((?:${IMAGE_UNIT}[ \t]*)+?)[ \t]*(?:\*\*|__)*[ \t]*$`);
1423
+ var SECTION_NUMBER_RE = /^(?:\*\*|__)?\s*(0[1-9]|1[0-9])\s*(?:\*\*|__)?$/;
1424
+ var SECTION_HEADING_RE = /^(#{1,6})\s+(\S.*)$/;
1425
+ var SECTION_BOLD_RE = /^(\*\*|__)(?!\s)([^*_\n]+?)(?<!\s)\1$/;
1426
+ var ORNAMENT_WORD_RE = /^(?:\*\*|__)?\s*(?:PART|CASE)\s*(?:\*\*|__)?$/;
1427
+ function cleanWechatDecorations(markdown) {
1428
+ const lines = markdown.split("\n");
1429
+ const out = [];
1430
+ let fence = null;
1431
+ for (let index = 0; index < lines.length; index += 1) {
1432
+ const line = lines[index] ?? "";
1433
+ const marker = /^\s{0,3}(`{3,}|~{3,})\s*([\w-]*)\s*$/.exec(line);
1434
+ if (fence) {
1435
+ out.push(line);
1436
+ if (marker && marker[1][0] === fence.marker[0] && marker[1].length >= fence.marker.length && !marker[2]) {
1437
+ if (fence.language === "css" && !looksLikeCss(out.slice(fence.start + 1, out.length - 1).join("\n"))) {
1438
+ out[fence.start] = out[fence.start].replace(/css\s*$/i, "");
1439
+ }
1440
+ fence = null;
1441
+ }
1442
+ continue;
1443
+ }
1444
+ if (marker) {
1445
+ fence = { language: (marker[2] ?? "").toLowerCase(), marker: marker[1], start: out.length };
1446
+ out.push(line);
1447
+ continue;
1448
+ }
1449
+ const wrapped = BOLD_WRAPPED_IMAGE_LINE_RE.exec(line);
1450
+ if (wrapped && !(lines[index + 1] ?? "").trim()) {
1451
+ out.push(`${wrapped[1] ?? ""}${(wrapped[2] ?? "").trim()}`);
1452
+ continue;
1453
+ }
1454
+ if (isIsolated(lines, index)) {
1455
+ const trimmed = line.trim();
1456
+ const nextIndex = nextNonBlank(lines, index + 1);
1457
+ const next = nextIndex >= 0 ? (lines[nextIndex] ?? "").trim() : "";
1458
+ const number = SECTION_NUMBER_RE.exec(trimmed)?.[1];
1459
+ if (number && nextIndex >= 0) {
1460
+ const afterIndex = ORNAMENT_WORD_RE.test(next) && isIsolated(lines, nextIndex) ? nextNonBlank(lines, nextIndex + 1) : -1;
1461
+ const afterMerged = afterIndex >= 0 ? mergeSectionNumber(number, (lines[afterIndex] ?? "").trim()) : null;
1462
+ if (afterMerged) {
1463
+ out.push(afterMerged);
1464
+ index = afterIndex;
1465
+ continue;
1466
+ }
1467
+ const merged = mergeSectionNumber(number, next);
1468
+ if (merged) {
1469
+ out.push(merged);
1470
+ index = nextIndex;
1471
+ continue;
1472
+ }
1473
+ }
1474
+ if (ORNAMENT_WORD_RE.test(trimmed) && !SECTION_NUMBER_RE.test(next) && !isSectionTitle(next)) {
1475
+ index += 1;
1476
+ continue;
1477
+ }
1478
+ }
1479
+ out.push(line);
1480
+ }
1481
+ return out.join("\n");
1482
+ }
1483
+ function nextNonBlank(lines, from) {
1484
+ for (let index = from; index < lines.length; index += 1) {
1485
+ if ((lines[index] ?? "").trim()) return index;
1486
+ }
1487
+ return -1;
1488
+ }
1489
+ function isSectionTitle(line) {
1490
+ return SECTION_HEADING_RE.test(line) || SECTION_BOLD_RE.test(line);
1491
+ }
1492
+ function mergeSectionNumber(number, title) {
1493
+ const heading = SECTION_HEADING_RE.exec(title);
1494
+ if (heading) return `${heading[1]} ${number} ${heading[2]}`;
1495
+ const bold = SECTION_BOLD_RE.exec(title);
1496
+ if (bold) return `${bold[1]}${number} ${bold[2]}${bold[1]}`;
1497
+ return null;
1498
+ }
1499
+ function isIsolated(lines, index) {
1500
+ return !(lines[index - 1] ?? "").trim() && !(lines[index + 1] ?? "").trim() && Boolean((lines[index] ?? "").trim());
1501
+ }
1502
+ function looksLikeCss(code) {
1503
+ return /[{}]/.test(code) || /^\s*[\w-]+\s*:\s*[^;\n]+;\s*$/m.test(code) || /^\s*@(?:media|import|keyframes|font-face)\b/m.test(code);
1504
+ }
1505
+
1506
+ // ../../packages/clip-engine/src/clip/wechat.ts
1507
+ async function extractWechatClip(url, ctx) {
1508
+ const { captureTimeoutMs, media } = clipEngineConfig();
1509
+ logInfo("wechat-article.runner", "run.start", { timeoutMs: captureTimeoutMs, url, workDir: ctx.workDir });
1510
+ const capture = await captureWechatArticleHtml(url, { timeoutMs: captureTimeoutMs });
1511
+ const parsed = parseWechatArticleHtml(capture.html, { sourceUrl: capture.finalUrl || capture.url });
1512
+ const imageAssets = await downloadWechatArticleImages({
1513
+ concurrency: media.imageConcurrency,
1514
+ imageDir: ctx.workDir,
1515
+ imagePathPrefix: "images",
1516
+ imageUrls: parsed.imageUrls,
1517
+ maxImageBytes: media.maxImageBytes,
1518
+ retries: media.downloadRetries
1519
+ });
1520
+ if (imageAssets.failed.length > 0) {
1521
+ logWarn("wechat-article.runner", "image.download.partial", {
1522
+ downloaded: imageAssets.downloaded.length,
1523
+ failed: imageAssets.failed.length,
1524
+ ...summarizeImageFailures(imageAssets.failed)
1525
+ });
1526
+ }
1527
+ const body = convertWechatContentHtmlToMarkdown(parsed.contentHtml, parsed.codeBlocks);
1528
+ const { metadata } = parsed;
1529
+ const rawMarkdown = normalizeWechatArticleMarkdown(buildWechatArticleMarkdown(metadata, body), metadata);
1530
+ const markdown = normalizeWechatArticleMarkdown(
1531
+ buildWechatArticleMarkdown(metadata, replaceWechatMarkdownImageUrls(body, imageAssets.urlMap)),
1532
+ metadata
1533
+ );
1534
+ logInfo("wechat-article.runner", "extract.ok", {
1535
+ images: imageAssets.downloaded.length,
1536
+ imageUrls: parsed.imageUrls.length,
1537
+ selectorFound: capture.selectorFound,
1538
+ title: metadata.title
1539
+ });
1540
+ return {
1541
+ author: metadata.author,
1542
+ markdown,
1543
+ publishTime: metadata.publishTime,
1544
+ rawMarkdown,
1545
+ sourceUrl: metadata.sourceUrl,
1546
+ title: metadata.title
1547
+ };
1548
+ }
1549
+ export {
1550
+ extractWechatClip
1551
+ };