@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,1833 @@
1
+ import { createRequire as __dinoxCreateRequire } from 'node:module';
2
+ const require = __dinoxCreateRequire(import.meta.url);
3
+ import {
4
+ XiaohongshuToMarkdownError,
5
+ alternateXiaohongshuShortLinkUrl,
6
+ assertXiaohongshuUrl,
7
+ isXiaohongshuNoteUrl,
8
+ isXiaohongshuShortLinkUrl,
9
+ normalizeXiaohongshuUrl,
10
+ toXiaohongshuExploreUrl,
11
+ xiaohongshuNonNotePageKind
12
+ } from "./chunk-XFVLNCOW.js";
13
+ import {
14
+ detectCaptureBlock,
15
+ isDecorativeEmojiImage
16
+ } from "./chunk-N44NRKDJ.js";
17
+ import {
18
+ launchBrowser
19
+ } from "./chunk-W7R5JTSA.js";
20
+ import {
21
+ summarizeImageFailures
22
+ } from "./chunk-5KU25TMX.js";
23
+ import {
24
+ isTransientError,
25
+ retry
26
+ } from "./chunk-QZQRG3JY.js";
27
+ import {
28
+ composeClipMarkdown
29
+ } from "./chunk-FIQYJ6KZ.js";
30
+ import "./chunk-XMMTGPZ6.js";
31
+ import "./chunk-URYABAYN.js";
32
+ import {
33
+ clipEngineConfig
34
+ } from "./chunk-F7BDWXBG.js";
35
+ import "./chunk-AHRCI2RW.js";
36
+ import "./chunk-6VMHHE5Y.js";
37
+ import {
38
+ logInfo,
39
+ logWarn
40
+ } from "./chunk-KOAKG2QU.js";
41
+ import "./chunk-XQZUX7OT.js";
42
+
43
+ // ../../packages/clip-engine/src/xiaohongshuToMarkdown/assets.ts
44
+ import { mkdir, writeFile } from "node:fs/promises";
45
+ import { dirname, join, posix } from "node:path";
46
+ var DEFAULT_CONCURRENCY = 4;
47
+ var DEFAULT_TIMEOUT_MS = 2e4;
48
+ var DEFAULT_MAX_BYTES = 50 * 1024 * 1024;
49
+ var DEFAULT_RETRIES = 3;
50
+ var DEFAULT_REFERER = "https://www.xiaohongshu.com/";
51
+ var DEFAULT_AUDIO_PATH_PREFIX = "audio";
52
+ var DEFAULT_IMAGE_PATH_PREFIX = "images";
53
+ var DEFAULT_VIDEO_PATH_PREFIX = "videos";
54
+ async function downloadXiaohongshuMedia(options) {
55
+ const media = uniqueMedia(filterMediaTypes(options.media, options.mediaTypes));
56
+ if (!media.length) return emptyResult();
57
+ await mkdir(options.mediaDir, { recursive: true });
58
+ const results = await mapWithConcurrency(
59
+ media,
60
+ Math.max(1, options.concurrency ?? DEFAULT_CONCURRENCY),
61
+ (item, index) => downloadOne(item, index + 1, options)
62
+ );
63
+ const downloaded = [];
64
+ const failed = [];
65
+ for (const result of results) {
66
+ if ("download" in result) downloaded.push(result.download);
67
+ else failed.push(result.failure);
68
+ }
69
+ return {
70
+ downloaded,
71
+ failed,
72
+ urlMap: new Map(downloaded.map((item) => [item.remoteUrl, item.localPath]))
73
+ };
74
+ }
75
+ var DEFAULT_VIDEO_FALLBACK_DELAY_MS = 1500;
76
+ var DEFAULT_VIDEO_MAX_CANDIDATES = 4;
77
+ async function downloadXiaohongshuVideoWithFallback(options) {
78
+ const { fallbackDelayMs, maxCandidates, onFallback, video, ...downloadOptions } = options;
79
+ const candidates = Array.from(
80
+ new Set([video.url, ...video.fallbackUrls ?? []].map((url) => url.trim()).filter(Boolean))
81
+ ).slice(0, Math.max(1, maxCandidates ?? DEFAULT_VIDEO_MAX_CANDIDATES));
82
+ const failures = [];
83
+ for (const [index, url] of candidates.entries()) {
84
+ const previous = failures.at(-1);
85
+ if (index > 0 && previous) {
86
+ onFallback?.(previous, url);
87
+ await delay(fallbackDelayMs ?? DEFAULT_VIDEO_FALLBACK_DELAY_MS);
88
+ }
89
+ const result = await downloadXiaohongshuMedia({
90
+ ...downloadOptions,
91
+ media: [{ type: "video", url, ...video.durationSeconds ? { durationSeconds: video.durationSeconds } : {} }],
92
+ mediaTypes: ["video"]
93
+ });
94
+ const download = result.downloaded[0];
95
+ if (download) return { download, failures };
96
+ failures.push(result.failed[0] ?? { message: "download did not produce a file", remoteUrl: url, type: "video" });
97
+ }
98
+ return { failures };
99
+ }
100
+ function delay(ms) {
101
+ return ms > 0 ? new Promise((resolve) => setTimeout(resolve, ms)) : Promise.resolve();
102
+ }
103
+ function emptyResult() {
104
+ return {
105
+ downloaded: [],
106
+ failed: [],
107
+ urlMap: /* @__PURE__ */ new Map()
108
+ };
109
+ }
110
+ async function downloadOne(media, index, options) {
111
+ try {
112
+ const { buffer, contentType } = await retry(() => fetchMedia(media, options), {
113
+ attempts: Math.max(1, options.retries ?? DEFAULT_RETRIES),
114
+ isRetryable: isTransientError
115
+ });
116
+ const fileName = buildFileName(media, index, contentType);
117
+ const localPath = posix.join(resolvePathPrefix(media, options), fileName);
118
+ const filePath = join(options.mediaDir, ...localPath.split("/"));
119
+ await mkdir(dirname(filePath), { recursive: true });
120
+ await writeFile(filePath, buffer);
121
+ return {
122
+ download: {
123
+ bytes: buffer.byteLength,
124
+ contentType,
125
+ ...media.durationSeconds ? { durationSeconds: media.durationSeconds } : {},
126
+ fileName,
127
+ localPath,
128
+ remoteUrl: media.url,
129
+ type: media.type
130
+ }
131
+ };
132
+ } catch (error) {
133
+ return {
134
+ failure: {
135
+ message: error instanceof Error ? error.message : String(error),
136
+ remoteUrl: media.url,
137
+ type: media.type
138
+ }
139
+ };
140
+ }
141
+ }
142
+ async function fetchMedia(media, options) {
143
+ const response = await fetchWithTimeout(media.url, options);
144
+ if (!response.ok) {
145
+ await discardBody(response);
146
+ const error = new Error(`HTTP ${response.status}`);
147
+ error.status = response.status;
148
+ throw error;
149
+ }
150
+ const maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;
151
+ const contentLength = Number.parseInt(response.headers.get("content-length") ?? "", 10);
152
+ if (Number.isFinite(contentLength) && contentLength > maxBytes) {
153
+ await discardBody(response);
154
+ throw new Error(`media exceeds max size (${contentLength}/${maxBytes})`);
155
+ }
156
+ const buffer = Buffer.from(await response.arrayBuffer());
157
+ if (buffer.byteLength > maxBytes) throw new Error(`media exceeds max size (${buffer.byteLength}/${maxBytes})`);
158
+ const contentType = normalizeMediaContentType(response.headers.get("content-type") ?? "", media.type);
159
+ return { buffer, contentType };
160
+ }
161
+ async function discardBody(response) {
162
+ await response.body?.cancel().catch(() => void 0);
163
+ }
164
+ async function fetchWithTimeout(url, options) {
165
+ const controller = new AbortController();
166
+ const timer = setTimeout(() => controller.abort(), options.timeoutMs ?? DEFAULT_TIMEOUT_MS);
167
+ const fetcher = options.fetcher ?? fetch;
168
+ try {
169
+ return await fetcher(url, {
170
+ headers: {
171
+ Referer: options.referer ?? DEFAULT_REFERER
172
+ },
173
+ signal: controller.signal
174
+ });
175
+ } finally {
176
+ clearTimeout(timer);
177
+ }
178
+ }
179
+ function buildFileName(media, index, contentType) {
180
+ const prefix = media.type === "video" ? "video" : media.type === "audio" ? "audio" : "image";
181
+ return `${prefix}_${String(index).padStart(3, "0")}.${inferExtension(media.url, contentType, media.type)}`;
182
+ }
183
+ function inferExtension(url, contentType, type) {
184
+ const mime = contentType.match(/^(?:audio|image|video)\/([a-z0-9.+-]+)/i)?.[1];
185
+ const path = url.match(/\.([a-z0-9]{3,4})(?:[!?#]|$)/i)?.[1];
186
+ const ext = (mime ?? path ?? defaultExtension(type)).toLowerCase();
187
+ if (ext === "jpeg") return "jpg";
188
+ if (ext === "quicktime") return "mov";
189
+ if (ext === "mpeg") return "mp3";
190
+ if (ext === "mp4" && type === "audio") return "m4a";
191
+ return ext.replace(/[^a-z0-9]/g, "") || defaultExtension(type);
192
+ }
193
+ function defaultExtension(type) {
194
+ if (type === "video") return "mp4";
195
+ if (type === "audio") return "m4a";
196
+ return "jpg";
197
+ }
198
+ function normalizeMediaContentType(value, type) {
199
+ const normalized = value.split(";")[0]?.trim().toLowerCase() ?? "";
200
+ if (normalized.startsWith(`${type}/`)) return normalized;
201
+ if (type === "video") return "video/mp4";
202
+ if (type === "audio") {
203
+ if (normalized.includes("mpeg")) return "audio/mpeg";
204
+ if (normalized.includes("aac")) return "audio/aac";
205
+ return "audio/mp4";
206
+ }
207
+ return "image/jpeg";
208
+ }
209
+ function uniqueMedia(media) {
210
+ const seen = /* @__PURE__ */ new Set();
211
+ const output = [];
212
+ for (const item of media) {
213
+ const key = `${item.type}:${item.url.trim()}`;
214
+ if (!item.url.trim() || seen.has(key)) continue;
215
+ seen.add(key);
216
+ output.push({
217
+ type: item.type,
218
+ url: item.url.trim(),
219
+ ...item.durationSeconds ? { durationSeconds: item.durationSeconds } : {}
220
+ });
221
+ }
222
+ return output;
223
+ }
224
+ function filterMediaTypes(media, mediaTypes) {
225
+ if (!mediaTypes?.length) return media;
226
+ const allowed = new Set(mediaTypes);
227
+ return media.filter((item) => allowed.has(item.type));
228
+ }
229
+ function resolvePathPrefix(media, options) {
230
+ if (options.mediaPathPrefix) return options.mediaPathPrefix;
231
+ if (media.type === "image") return options.imagePathPrefix ?? DEFAULT_IMAGE_PATH_PREFIX;
232
+ if (media.type === "audio") return options.audioPathPrefix ?? DEFAULT_AUDIO_PATH_PREFIX;
233
+ return options.videoPathPrefix ?? DEFAULT_VIDEO_PATH_PREFIX;
234
+ }
235
+ async function mapWithConcurrency(items, concurrency, mapper) {
236
+ const results = new Array(items.length);
237
+ let cursor = 0;
238
+ const workers = Array.from({ length: Math.min(concurrency, items.length) }, async () => {
239
+ while (cursor < items.length) {
240
+ const index = cursor;
241
+ cursor += 1;
242
+ results[index] = await mapper(items[index], index);
243
+ }
244
+ });
245
+ await Promise.all(workers);
246
+ return results;
247
+ }
248
+
249
+ // ../../packages/clip-engine/src/xiaohongshuToMarkdown/parse.ts
250
+ import * as cheerio from "cheerio";
251
+ var MAX_VIDEO_FALLBACKS = 3;
252
+ var NOISE_SELECTORS = [
253
+ "script",
254
+ "style",
255
+ "#detail-title",
256
+ "#comments",
257
+ ".comments-el",
258
+ ".interactions",
259
+ ".engage-bar",
260
+ ".engage-bar-container",
261
+ ".author",
262
+ ".author-container",
263
+ ".tips-el",
264
+ ".comment-item",
265
+ ".reply-container",
266
+ ".show-more"
267
+ ].join(",");
268
+ function parseXiaohongshuHtml(html, options = {}) {
269
+ if (isLoginWall(html, options.sourceUrl ?? "")) {
270
+ throw new XiaohongshuToMarkdownError("LOGIN_WALL", "Xiaohongshu redirected to login wall", {
271
+ url: options.sourceUrl
272
+ });
273
+ }
274
+ const nonNote = xiaohongshuNonNotePageKind(options.sourceUrl ?? "");
275
+ if (nonNote) {
276
+ throw new XiaohongshuToMarkdownError("UNSUPPORTED_CONTENT_TYPE", `xiaohongshu link opens a ${nonNote}, not a single note`, {
277
+ url: options.sourceUrl
278
+ });
279
+ }
280
+ const $ = cheerio.load(html);
281
+ const stateNote = extractStateNoteData(html);
282
+ const content = selectContent($);
283
+ const domHasBody = content.length > 0;
284
+ const contentHtml = domHasBody ? cleanContentHtml($, content) : buildParagraphHtml(stateNote.description);
285
+ const text = domHasBody ? extractContentText($, content) : stateNote.description;
286
+ const normalizedText = normalizeText(text);
287
+ const metadata = extractMetadata($, {
288
+ sourceUrl: options.sourceUrl ?? "",
289
+ stateNote,
290
+ text: normalizedText
291
+ });
292
+ const media = extractMedia($, html, stateNote);
293
+ if (!normalizedText && media.length === 0) {
294
+ throw new XiaohongshuToMarkdownError("CONTENT_NOT_FOUND", "could not extract Xiaohongshu note content", {
295
+ url: options.sourceUrl
296
+ });
297
+ }
298
+ return {
299
+ contentHtml,
300
+ media,
301
+ metadata,
302
+ text: normalizedText
303
+ };
304
+ }
305
+ function hasParseableXiaohongshuNote(html, sourceUrl = "") {
306
+ try {
307
+ const parsed = parseXiaohongshuHtml(html, { sourceUrl });
308
+ return Boolean(parsed.text || parsed.media.length > 0);
309
+ } catch {
310
+ return false;
311
+ }
312
+ }
313
+ function xiaohongshuCaptureNeedsAudioHydration(html, sourceUrl = "") {
314
+ try {
315
+ const parsed = parseXiaohongshuHtml(html, { sourceUrl });
316
+ if (parsed.media.some((item) => item.type === "audio")) return false;
317
+ return looksLikeXiaohongshuAudioBlog(html, parsed);
318
+ } catch {
319
+ return looksLikeXiaohongshuAudioBlog(html);
320
+ }
321
+ }
322
+ function injectXiaohongshuClipAudio(html, audio) {
323
+ const payload = JSON.stringify({
324
+ ...audio.durationSeconds ? { durationSeconds: audio.durationSeconds } : {},
325
+ url: audio.url
326
+ });
327
+ const snippet = `<script>window.__XHS_CLIP_AUDIO__ = ${payload}</script>`;
328
+ if (/window\.__XHS_CLIP_AUDIO__\s*=/.test(html)) {
329
+ return html.replace(/window\.__XHS_CLIP_AUDIO__\s*=\s*\{[\s\S]*?\}/, `window.__XHS_CLIP_AUDIO__ = ${payload}`);
330
+ }
331
+ if (html.includes("</body>")) return html.replace("</body>", `${snippet}</body>`);
332
+ return `${html}${snippet}`;
333
+ }
334
+ function collectXiaohongshuAudioFromUnknown(value) {
335
+ const found = [];
336
+ walkUnknown(value, (record) => {
337
+ if ("audioInfo" in record) found.push(...collectAudioFromInfo(record.audioInfo));
338
+ if (isRecord(record.playInfo) || /^(?:audio|podcast)$/i.test(getString(record.type))) {
339
+ found.push(...collectAudioFromInfo(record));
340
+ }
341
+ });
342
+ return uniqueAudioRefs(found);
343
+ }
344
+ function selectContent($) {
345
+ const primary = $("#detail-desc").first();
346
+ if (primary.length) return primary;
347
+ return $(".note-content").first();
348
+ }
349
+ function cleanContentHtml($, content) {
350
+ const clone = content.clone();
351
+ clone.find(NOISE_SELECTORS).remove();
352
+ clone.find("img").each((_, element) => {
353
+ if (isDecorativeHtmlImage($, element)) $(element).remove();
354
+ });
355
+ clone.find("br").replaceWith("<br>");
356
+ return $.html(clone).trim();
357
+ }
358
+ function extractContentText($, content) {
359
+ const noteTextParts = content.find(".note-text").toArray().map((node) => $(node).text().trim()).filter(Boolean);
360
+ if (noteTextParts.length) return noteTextParts.join("\n");
361
+ return content.text();
362
+ }
363
+ function extractMetadata($, input) {
364
+ const domTitle = normalizeTitle($("#detail-title").first().text());
365
+ const stateTitle = normalizeTitle(input.stateNote.title);
366
+ const textTitle = deriveTitleFromText(input.text);
367
+ const ogTitle = normalizeTitle($('meta[property="og:title"], meta[name="og:title"]').first().attr("content") ?? "");
368
+ const docTitle = normalizeTitle($("title").first().text());
369
+ const author = normalizeText(input.stateNote.author) || normalizeText($(".author .name, .user-name, .nickname").first().text()) || normalizeText($('meta[name="author"]').first().attr("content") ?? "");
370
+ return {
371
+ author,
372
+ publishTime: input.stateNote.publishTime || normalizeText($(".date").first().text()),
373
+ sourceUrl: input.sourceUrl,
374
+ title: domTitle || stateTitle || textTitle || ogTitle || docTitle || "\u5C0F\u7EA2\u4E66\u7B14\u8BB0"
375
+ };
376
+ }
377
+ function extractMedia($, html, stateNote) {
378
+ const imageUrls = normalizeMediaUrls([
379
+ ...extractDomImages($),
380
+ ...extractMetaValues($, "og:image"),
381
+ ...stateNote.images,
382
+ ...extractRawImageUrls(html)
383
+ ]);
384
+ const videoUrls = normalizeMediaUrls([
385
+ ...extractDomVideos($),
386
+ ...extractMetaValues($, "og:video"),
387
+ ...stateNote.videos
388
+ ]);
389
+ const audios = uniqueAudioRefs([
390
+ ...extractClipAudio(html),
391
+ ...stateNote.audios,
392
+ ...extractDomAudios($),
393
+ ...extractMetaValues($, "og:audio").map((url) => ({ url }))
394
+ ]);
395
+ return [
396
+ ...imageUrls.map((url) => ({ type: "image", url })),
397
+ ...videoUrls.map((url, index) => {
398
+ const fallbackUrls = index === 0 ? buildVideoFallbacks(url, stateNote.videoCandidates) : [];
399
+ return { type: "video", url, ...fallbackUrls.length ? { fallbackUrls } : {} };
400
+ }),
401
+ ...audios.map((audio) => ({
402
+ type: "audio",
403
+ url: audio.url,
404
+ ...audio.durationSeconds ? { durationSeconds: audio.durationSeconds } : {}
405
+ }))
406
+ ];
407
+ }
408
+ function extractDomImages($) {
409
+ const urls = [];
410
+ $('.media-container img, [class*="media"] img').each((_, element) => {
411
+ if (isDecorativeHtmlImage($, element)) return;
412
+ const src = $(element).attr("src") || $(element).attr("data-src");
413
+ if (src) urls.push(src);
414
+ });
415
+ $('[style*="background-image"]').each((_, element) => {
416
+ const style = $(element).attr("style") ?? "";
417
+ for (const match of style.matchAll(/background-image\s*:\s*url\(([^)]+)\)/gi)) {
418
+ if (match[1]) urls.push(match[1].replace(/^['"]|['"]$/g, ""));
419
+ }
420
+ });
421
+ return urls;
422
+ }
423
+ function isDecorativeHtmlImage($, element) {
424
+ const image = $(element);
425
+ const size = readImageSize(image);
426
+ return isDecorativeEmojiImage({
427
+ alt: image.attr("alt"),
428
+ className: image.attr("class"),
429
+ height: size.height,
430
+ role: image.attr("role"),
431
+ src: image.attr("src") || image.attr("data-src"),
432
+ title: image.attr("title"),
433
+ width: size.width
434
+ });
435
+ }
436
+ function extractDomVideos($) {
437
+ const urls = [];
438
+ $(".media-container video, .media-container source, video, source").each((_, element) => {
439
+ const src = $(element).attr("src");
440
+ if (src) urls.push(src);
441
+ });
442
+ return urls;
443
+ }
444
+ function extractDomAudios($) {
445
+ const urls = [];
446
+ $("audio, audio source").each((_, element) => {
447
+ const src = $(element).attr("src");
448
+ if (src) urls.push(src);
449
+ });
450
+ return uniqueAudioRefs(urls.map((url) => ({ url })));
451
+ }
452
+ function extractMetaValues($, key) {
453
+ return $(`meta[property="${key}"], meta[name="${key}"]`).toArray().flatMap((element) => {
454
+ const value = $(element).attr("content")?.trim();
455
+ return value ? [value] : [];
456
+ });
457
+ }
458
+ function extractRawImageUrls(html) {
459
+ return [
460
+ ...Array.from(html.matchAll(/"urlDefault"\s*:\s*"([^"]+)"/gi), (match) => decodeEscapedUrl(match[1] ?? "")),
461
+ ...Array.from(html.matchAll(/"urlPre"\s*:\s*"([^"]+)"/gi), (match) => decodeEscapedUrl(match[1] ?? ""))
462
+ ];
463
+ }
464
+ function extractStateNoteData(html) {
465
+ const stateRoot = extractStateRoot(html);
466
+ const note = extractPrimaryNoteFromState(stateRoot);
467
+ return {
468
+ audios: uniqueAudioRefs([...extractClipAudio(html), ...collectStateAudios(note)]),
469
+ author: readStateAuthor(note),
470
+ description: normalizeText(getString(note?.desc) || getString(note?.description)),
471
+ images: collectStateImages(note),
472
+ publishTime: readStatePublishTime(note),
473
+ title: normalizeTitle(getString(note?.title) || getString(note?.displayTitle)),
474
+ videoCandidates: collectStateVideoCandidates(note),
475
+ videos: collectStateVideos(note)
476
+ };
477
+ }
478
+ function extractStateRoot(html) {
479
+ for (const globalName of ["window.__INITIAL_STATE__", "__INITIAL_STATE__"]) {
480
+ const assignmentIndex = html.indexOf(globalName);
481
+ if (assignmentIndex < 0) continue;
482
+ const jsonStart = html.indexOf("{", assignmentIndex);
483
+ if (jsonStart < 0) continue;
484
+ const jsonText = sliceBalancedJson(html, jsonStart);
485
+ if (!jsonText) continue;
486
+ try {
487
+ const parsed = JSON.parse(sanitizeStateJson(jsonText));
488
+ if (isRecord(parsed)) return parsed;
489
+ } catch {
490
+ }
491
+ }
492
+ return null;
493
+ }
494
+ function sanitizeStateJson(jsonText) {
495
+ return jsonText.replace(
496
+ /([:,[])(\s*)(?:-?Infinity|NaN|undefined)(?=\s*[,\]}])/g,
497
+ "$1$2null"
498
+ );
499
+ }
500
+ function sliceBalancedJson(text, startIndex) {
501
+ let depth = 0;
502
+ let quote = "";
503
+ let escaped = false;
504
+ for (let index = startIndex; index < text.length; index += 1) {
505
+ const char = text[index];
506
+ if (quote) {
507
+ if (escaped) {
508
+ escaped = false;
509
+ } else if (char === "\\") {
510
+ escaped = true;
511
+ } else if (char === quote) {
512
+ quote = "";
513
+ }
514
+ continue;
515
+ }
516
+ if (char === '"' || char === "'") {
517
+ quote = char;
518
+ continue;
519
+ }
520
+ if (char === "{") depth += 1;
521
+ if (char === "}") {
522
+ depth -= 1;
523
+ if (depth === 0) return text.slice(startIndex, index + 1);
524
+ }
525
+ }
526
+ return null;
527
+ }
528
+ function extractPrimaryNoteFromState(stateRoot) {
529
+ const fromLegacyStore = extractNoteFromLegacyStore(getNestedRecord(stateRoot, ["note"]));
530
+ if (fromLegacyStore) return fromLegacyStore;
531
+ const fromNoteData = getNestedRecord(stateRoot, ["noteData", "data", "noteData"]);
532
+ if (fromNoteData && isUsableNoteRecord(fromNoteData)) return fromNoteData;
533
+ const preload = getNestedRecord(stateRoot, ["noteData", "normalNotePreloadData"]);
534
+ if (preload && isUsableNoteRecord(preload)) return preload;
535
+ return null;
536
+ }
537
+ function extractNoteFromLegacyStore(noteStore) {
538
+ if (!noteStore) return null;
539
+ const currentNoteId = getString(noteStore.currentNoteId) || getString(noteStore.firstNoteId);
540
+ const detailMap = getNestedRecord(noteStore, ["noteDetailMap"]);
541
+ if (detailMap && currentNoteId) {
542
+ const note = getNestedRecord(getNestedRecord(detailMap, [currentNoteId]), ["note"]);
543
+ if (note) return note;
544
+ }
545
+ if (detailMap) {
546
+ for (const entry of Object.values(detailMap)) {
547
+ const note = getNestedRecord(isRecord(entry) ? entry : null, ["note"]);
548
+ if (note) return note;
549
+ }
550
+ }
551
+ return getNestedRecord(noteStore, ["note"]);
552
+ }
553
+ function isUsableNoteRecord(note) {
554
+ return Boolean(
555
+ getString(note.title) || getString(note.displayTitle) || getString(note.desc) || getString(note.description) || Array.isArray(note.imageList) && note.imageList.length > 0 || Array.isArray(note.imagesList) && note.imagesList.length > 0 || isRecord(note.audioInfo) || isRecord(note.video) || /^(?:audio|podcast)$/i.test(getString(note.type))
556
+ );
557
+ }
558
+ function collectStateImages(note) {
559
+ const imageList = Array.isArray(note?.imageList) ? note.imageList : Array.isArray(note?.imagesList) ? note.imagesList : [];
560
+ const urls = [];
561
+ for (const image of imageList) {
562
+ if (!isRecord(image)) continue;
563
+ const picked = pickBestStateImage(image);
564
+ if (isDecorativeEmojiImage({ ...readStateImageSize(image), src: picked })) continue;
565
+ if (picked) urls.push(picked);
566
+ }
567
+ return normalizeMediaUrls(urls);
568
+ }
569
+ function pickBestStateImage(image) {
570
+ const webUrls = [];
571
+ const infoList = Array.isArray(image.infoList) ? image.infoList : [];
572
+ for (const info of infoList) {
573
+ if (!isRecord(info)) continue;
574
+ if (/dft|h5_dtl/i.test(getString(info.imageScene))) {
575
+ webUrls.push(decodeEscapedUrl(getString(info.url)));
576
+ }
577
+ }
578
+ webUrls.push(decodeEscapedUrl(getString(image.urlDefault)));
579
+ webUrls.push(decodeEscapedUrl(getString(image.url)));
580
+ webUrls.push(decodeEscapedUrl(getString(image.urlPre)));
581
+ const fileId = getString(image.fileId).trim() || getString(image.traceId).trim() || webUrls.map(extractXiaohongshuFileId).find(Boolean) || "";
582
+ const originalUrl = buildXiaohongshuOriginalImageUrl(fileId);
583
+ return normalizeMediaUrls(originalUrl ? [originalUrl, ...webUrls] : webUrls)[0] ?? "";
584
+ }
585
+ function extractXiaohongshuFileId(rawUrl) {
586
+ try {
587
+ const parsed = new URL(toHttps(decodeEscapedUrl(rawUrl)));
588
+ const path = decodeURIComponent(parsed.pathname);
589
+ const prefixed = path.match(/((?:oss-ae\/notes|notes_uhdr)\/[^/!]+)/i)?.[1];
590
+ if (prefixed) return prefixed;
591
+ const last = path.split("/").filter(Boolean).at(-1)?.split("!")[0] ?? "";
592
+ if (/^1040g[a-z0-9]+$/i.test(last)) return last;
593
+ if (/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(last)) return last;
594
+ return "";
595
+ } catch {
596
+ return "";
597
+ }
598
+ }
599
+ function buildXiaohongshuOriginalImageUrl(fileId) {
600
+ const id = fileId.replace(/^\/+/, "").trim();
601
+ if (!id) return "";
602
+ return `https://ci.xiaohongshu.com/${id}?imageView2/2/format/jpg`;
603
+ }
604
+ function collectStateVideos(note) {
605
+ const stream = getNestedRecord(note, ["video", "media", "stream"]);
606
+ if (!stream) return [];
607
+ const urls = [];
608
+ for (const codecStreams of Object.values(stream)) {
609
+ if (!Array.isArray(codecStreams)) continue;
610
+ for (const streamItem of codecStreams) {
611
+ if (!isRecord(streamItem)) continue;
612
+ urls.push(decodeEscapedUrl(getString(streamItem.masterUrl)));
613
+ const backupUrls = Array.isArray(streamItem.backupUrls) ? streamItem.backupUrls : [];
614
+ for (const backupUrl of backupUrls) {
615
+ if (typeof backupUrl === "string") urls.push(decodeEscapedUrl(backupUrl));
616
+ }
617
+ }
618
+ }
619
+ return normalizeMediaUrls(urls).slice(0, 1);
620
+ }
621
+ function collectStateVideoCandidates(note) {
622
+ const stream = getNestedRecord(note, ["video", "media", "stream"]);
623
+ if (!stream) return [];
624
+ const streams = [];
625
+ for (const codecStreams of Object.values(stream)) {
626
+ if (!Array.isArray(codecStreams)) continue;
627
+ for (const streamItem of codecStreams) {
628
+ if (!isRecord(streamItem)) continue;
629
+ const backupUrls = Array.isArray(streamItem.backupUrls) ? streamItem.backupUrls : [];
630
+ const urls = [getString(streamItem.masterUrl), ...backupUrls.filter((value) => typeof value === "string")];
631
+ const size = typeof streamItem.size === "number" && streamItem.size > 0 ? streamItem.size : Number.POSITIVE_INFINITY;
632
+ streams.push({ size, urls });
633
+ }
634
+ }
635
+ const [first, ...rest] = streams;
636
+ rest.sort((a, b) => a.size - b.size);
637
+ return uniqueExactUrls([...first?.urls ?? [], ...rest.flatMap((item) => item.urls)]);
638
+ }
639
+ function buildVideoFallbacks(primaryUrl, candidates) {
640
+ return candidates.filter((url) => url !== primaryUrl).slice(0, MAX_VIDEO_FALLBACKS);
641
+ }
642
+ function uniqueExactUrls(urls) {
643
+ const seen = /* @__PURE__ */ new Set();
644
+ const output = [];
645
+ for (const raw of urls) {
646
+ const url = toHttps(decodeEscapedUrl(raw.trim()));
647
+ if (!/^https:\/\//i.test(url) || seen.has(url)) continue;
648
+ seen.add(url);
649
+ output.push(url);
650
+ }
651
+ return output;
652
+ }
653
+ function collectStateAudios(note) {
654
+ if (!note) return [];
655
+ return uniqueAudioRefs([
656
+ ...collectAudioFromInfo(note.audioInfo),
657
+ ...collectAudioFromInfo(note.audio)
658
+ ]);
659
+ }
660
+ function collectAudioFromInfo(value) {
661
+ if (typeof value === "string") {
662
+ const url = normalizeAudioUrl(value);
663
+ return url ? [{ url }] : [];
664
+ }
665
+ if (!isRecord(value)) return [];
666
+ const playInfo = getNestedRecord(value, ["playInfo"]) ?? getNestedRecord(value, ["play_info"]);
667
+ const durationSeconds = readDurationSeconds(value) ?? (playInfo ? readDurationSeconds(playInfo) : void 0);
668
+ const urls = [
669
+ getString(playInfo?.url),
670
+ getString(playInfo?.masterUrl),
671
+ getString(value.url),
672
+ getString(value.audioUrl),
673
+ getString(value.masterUrl),
674
+ ...Array.isArray(playInfo?.backupUrls) ? playInfo.backupUrls : [],
675
+ ...Array.isArray(value.backupUrls) ? value.backupUrls : []
676
+ ];
677
+ return uniqueAudioRefs(
678
+ urls.flatMap((raw) => {
679
+ const url = normalizeAudioUrl(typeof raw === "string" ? raw : "");
680
+ return url ? [{ url, ...durationSeconds ? { durationSeconds } : {} }] : [];
681
+ })
682
+ );
683
+ }
684
+ function extractClipAudio(html) {
685
+ const assignmentIndex = html.indexOf("window.__XHS_CLIP_AUDIO__");
686
+ if (assignmentIndex < 0) return [];
687
+ const jsonStart = html.indexOf("{", assignmentIndex);
688
+ if (jsonStart < 0) return [];
689
+ const jsonText = sliceBalancedJson(html, jsonStart);
690
+ if (!jsonText) return [];
691
+ try {
692
+ return collectAudioFromInfo(JSON.parse(jsonText));
693
+ } catch {
694
+ return [];
695
+ }
696
+ }
697
+ function looksLikeXiaohongshuAudioBlog(html, parsed) {
698
+ if (/"type"\s*:\s*"(?:audio|podcast)"/i.test(html)) return true;
699
+ if (/"audioInfo"\s*:/.test(html)) return true;
700
+ const haystack = parsed ? `${parsed.metadata.title}
701
+ ${parsed.text}` : html;
702
+ return /播客|音频博客|本期节目/.test(haystack);
703
+ }
704
+ function walkUnknown(value, visit, depth = 0) {
705
+ if (depth > 8) return;
706
+ if (Array.isArray(value)) {
707
+ for (const item of value.slice(0, 20)) walkUnknown(item, visit, depth + 1);
708
+ return;
709
+ }
710
+ if (!isRecord(value)) return;
711
+ visit(value);
712
+ for (const nested of Object.values(value)) walkUnknown(nested, visit, depth + 1);
713
+ }
714
+ function uniqueAudioRefs(audios) {
715
+ const urls = normalizeMediaUrls(audios.map((item) => item.url));
716
+ const durationByUrl = /* @__PURE__ */ new Map();
717
+ for (const audio of audios) {
718
+ const url = normalizeMediaUrls([audio.url])[0];
719
+ if (!url || !audio.durationSeconds) continue;
720
+ durationByUrl.set(url, audio.durationSeconds);
721
+ }
722
+ return urls.slice(0, 1).map((url) => {
723
+ const durationSeconds = durationByUrl.get(url);
724
+ return durationSeconds ? { durationSeconds, url } : { url };
725
+ });
726
+ }
727
+ function normalizeAudioUrl(rawUrl) {
728
+ const url = toHttps(decodeEscapedUrl(rawUrl.trim()));
729
+ if (!url || url.startsWith("data:") || url.startsWith("blob:")) return "";
730
+ return url;
731
+ }
732
+ function readDurationSeconds(record) {
733
+ const raw = Number(
734
+ getString(record.durationSeconds) || getString(record.duration) || getString(record.durationMs)
735
+ );
736
+ if (!Number.isFinite(raw) || raw <= 0) return void 0;
737
+ return raw >= 1e3 ? Math.floor(raw / 1e3) : Math.floor(raw);
738
+ }
739
+ function readStateAuthor(note) {
740
+ const user = getNestedRecord(note, ["user"]);
741
+ return normalizeText(
742
+ getString(user?.nickname) || getString(user?.nickName) || getString(note?.nickname) || getString(note?.nickName)
743
+ );
744
+ }
745
+ function readStatePublishTime(note) {
746
+ const timestamp = Number(getString(note?.time) || getString(note?.lastUpdateTime));
747
+ if (!Number.isFinite(timestamp) || timestamp <= 0) return "";
748
+ const millis = timestamp > 1e10 ? timestamp : timestamp * 1e3;
749
+ return new Date(millis + 8 * 60 * 60 * 1e3).toISOString().slice(0, 19).replace("T", " ");
750
+ }
751
+ function readImageSize(image) {
752
+ const style = image.attr("style") ?? "";
753
+ const width = readPositiveNumber(image.attr("width")) ?? readStyleDimension(style, "width");
754
+ const height = readPositiveNumber(image.attr("height")) ?? readStyleDimension(style, "height");
755
+ return {
756
+ ...height ? { height } : {},
757
+ ...width ? { width } : {}
758
+ };
759
+ }
760
+ function readStateImageSize(image) {
761
+ const width = readPositiveNumber(getString(image.width)) ?? readPositiveNumber(getString(image.originalWidth)) ?? readPositiveNumber(getString(image.imageWidth));
762
+ const height = readPositiveNumber(getString(image.height)) ?? readPositiveNumber(getString(image.originalHeight)) ?? readPositiveNumber(getString(image.imageHeight));
763
+ return {
764
+ ...height ? { height } : {},
765
+ ...width ? { width } : {}
766
+ };
767
+ }
768
+ function readStyleDimension(style, name) {
769
+ return readPositiveNumber(style.match(new RegExp(`(?:^|;)\\s*${name}\\s*:\\s*([^;]+)`, "i"))?.[1]);
770
+ }
771
+ function readPositiveNumber(value) {
772
+ const matched = String(value ?? "").match(/(\d+(?:\.\d+)?)/)?.[1];
773
+ const parsed = Number(matched);
774
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : void 0;
775
+ }
776
+ function isXiaohongshuBrandingImage(url) {
777
+ try {
778
+ const parsed = new URL(url);
779
+ return parsed.hostname === "picasso-static.xiaohongshu.com" && parsed.pathname.startsWith("/fe-platform/");
780
+ } catch {
781
+ return false;
782
+ }
783
+ }
784
+ function isXiaohongshuKeylessImage(url) {
785
+ try {
786
+ const parsed = new URL(url);
787
+ return /(^|\.)(xiaohongshu\.com|xhscdn\.com)$/i.test(parsed.hostname) && /^\/*$/.test(parsed.pathname);
788
+ } catch {
789
+ return false;
790
+ }
791
+ }
792
+ function normalizeMediaUrls(urls) {
793
+ const bestByKey = /* @__PURE__ */ new Map();
794
+ for (const rawUrl of urls) {
795
+ const url = toHttps(unwrapXiaohongshuCiUrl(decodeEscapedUrl(String(rawUrl ?? "").trim())));
796
+ if (!url || url.startsWith("data:") || url.startsWith("blob:")) continue;
797
+ if (isDecorativeEmojiImage({ src: url })) continue;
798
+ if (isXiaohongshuBrandingImage(url)) continue;
799
+ if (isXiaohongshuKeylessImage(url)) continue;
800
+ const key = getMediaDedupKey(url);
801
+ const existing = bestByKey.get(key);
802
+ if (!existing || rankMediaVariant(url) > rankMediaVariant(existing)) bestByKey.set(key, url);
803
+ }
804
+ return Array.from(bestByKey.values());
805
+ }
806
+ function unwrapXiaohongshuCiUrl(value) {
807
+ try {
808
+ const parsed = new URL(value);
809
+ if (parsed.hostname !== "ci.xiaohongshu.com") return value;
810
+ const embeddedUrl = parsed.pathname.slice(1);
811
+ if (/^https?:\/\//i.test(embeddedUrl)) return embeddedUrl;
812
+ const decodedUrl = decodeURIComponent(embeddedUrl);
813
+ return /^https?:\/\//i.test(decodedUrl) ? decodedUrl : value;
814
+ } catch {
815
+ return value;
816
+ }
817
+ }
818
+ function getMediaDedupKey(rawUrl) {
819
+ try {
820
+ const parsed = new URL(rawUrl);
821
+ const lastSegment = parsed.pathname.split("/").filter(Boolean).at(-1) ?? "";
822
+ const stableId = lastSegment.split("!")[0];
823
+ if (stableId && (/(^|\.)xhscdn\.com$/i.test(parsed.hostname) || /^ci\.xiaohongshu\.com$/i.test(parsed.hostname))) {
824
+ return `xhs:${stableId}`;
825
+ }
826
+ return `${parsed.origin}${parsed.pathname}`;
827
+ } catch {
828
+ return rawUrl.split("?")[0]?.split("#")[0]?.split("!")[0] ?? rawUrl;
829
+ }
830
+ }
831
+ function rankMediaVariant(url) {
832
+ if (isXiaohongshuOriginalImageUrl(url)) return 200;
833
+ if (/!nd_dft(?:_|\b)/i.test(url)) return 100;
834
+ if (/[?&](?:sign|t)=/i.test(url)) return 80;
835
+ if (!/![^/?#]*$/.test(url)) return 60;
836
+ if (/!h5_1080/i.test(url)) return 15;
837
+ if (/!nd_prv(?:_|\b)/i.test(url)) return 10;
838
+ return 30;
839
+ }
840
+ function isXiaohongshuOriginalImageUrl(url) {
841
+ try {
842
+ const parsed = new URL(url);
843
+ if (parsed.hostname !== "ci.xiaohongshu.com") return false;
844
+ if (parsed.pathname.startsWith("/http")) return false;
845
+ return /(?:^|[?&])imageView2\/2\/format\/jpg(?:&|$)/i.test(parsed.search.replace(/^\?/, ""));
846
+ } catch {
847
+ return false;
848
+ }
849
+ }
850
+ function isLoginWall(html, url) {
851
+ if (/\/login(?:\b|\/|\?)/i.test(url)) return true;
852
+ return /\/login\?redirectPath=/i.test(html) || /<title>\s*登录\s*-\s*小红书\s*<\/title>/i.test(html);
853
+ }
854
+ function buildParagraphHtml(text) {
855
+ const body = normalizeText(text);
856
+ if (!body) return "";
857
+ return `<p>${escapeHtml(body).replace(/\n+/g, "<br>")}</p>`;
858
+ }
859
+ function deriveTitleFromText(text) {
860
+ const firstLine = text.split(/\n+/).map((line) => line.trim()).find(Boolean) ?? "";
861
+ return truncateTitle(firstLine);
862
+ }
863
+ function normalizeTitle(value) {
864
+ const cleaned = normalizeText(value).replace(/\s*-\s*小红书\s*$/u, "");
865
+ return truncateTitle(cleaned);
866
+ }
867
+ function truncateTitle(value) {
868
+ const normalized = value.trim();
869
+ return normalized.length > 80 ? `${normalized.slice(0, 77)}...` : normalized;
870
+ }
871
+ function normalizeText(value) {
872
+ return String(value ?? "").replace(/\u00a0/g, " ").replace(/[ \t]+\n/g, "\n").replace(/[ \t]{2,}/g, " ").trim();
873
+ }
874
+ function toHttps(value) {
875
+ if (value.startsWith("//")) return `https:${value}`;
876
+ return value.replace(/^http:\/\//i, "https://");
877
+ }
878
+ function decodeEscapedUrl(rawUrl) {
879
+ return rawUrl.replace(/\\\//g, "/").replace(/\\u([0-9a-fA-F]{4})/g, (_match, hex) => {
880
+ try {
881
+ return String.fromCodePoint(Number.parseInt(hex, 16));
882
+ } catch {
883
+ return _match;
884
+ }
885
+ });
886
+ }
887
+ function getNestedRecord(root, path) {
888
+ let current = root;
889
+ for (const key of path) {
890
+ if (!isRecord(current)) return null;
891
+ current = current[key];
892
+ }
893
+ return isRecord(current) ? current : null;
894
+ }
895
+ function getString(value) {
896
+ return typeof value === "string" || typeof value === "number" ? String(value) : "";
897
+ }
898
+ function isRecord(value) {
899
+ return typeof value === "object" && value !== null && !Array.isArray(value);
900
+ }
901
+ function escapeHtml(value) {
902
+ return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
903
+ }
904
+
905
+ // ../../packages/clip-engine/src/xiaohongshuToMarkdown/resolve.ts
906
+ var DEFAULT_RESOLVE_TIMEOUT_MS = 12e3;
907
+ var MAX_REDIRECT_HOPS = 8;
908
+ var RESOLVE_HEADERS = {
909
+ Accept: "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
910
+ "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
911
+ "Cache-Control": "no-cache",
912
+ Pragma: "no-cache",
913
+ Referer: "https://www.xiaohongshu.com/",
914
+ "User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 18_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.5 Mobile/15E148 Safari/604.1"
915
+ };
916
+ async function resolveXiaohongshuCaptureUrl(rawUrl, options = {}) {
917
+ const url = assertXiaohongshuUrl(rawUrl);
918
+ if (!isXiaohongshuShortLinkUrl(url)) {
919
+ return { cookies: [], resolved: false, url };
920
+ }
921
+ const candidates = uniqueUrls([url, alternateXiaohongshuShortLinkUrl(url)]);
922
+ for (const candidate of candidates) {
923
+ const resolved = await resolveXiaohongshuShortLinkHttpDetailed(candidate, options);
924
+ if (resolved.url) {
925
+ return {
926
+ cookies: resolved.cookies,
927
+ fromShortLink: url,
928
+ resolved: true,
929
+ url: resolved.url
930
+ };
931
+ }
932
+ }
933
+ return { cookies: [], fromShortLink: url, resolved: false, url };
934
+ }
935
+ async function fetchXiaohongshuPageHtml(rawUrl, options = {}) {
936
+ const url = assertXiaohongshuUrl(rawUrl);
937
+ if (!isXiaohongshuNoteUrl(url)) return null;
938
+ const fetcher = options.fetcher ?? fetch;
939
+ const timeoutMs = options.timeoutMs ?? DEFAULT_RESOLVE_TIMEOUT_MS;
940
+ const controller = new AbortController();
941
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
942
+ try {
943
+ const response = await fetcher(url, {
944
+ headers: {
945
+ ...RESOLVE_HEADERS,
946
+ ...options.cookies && options.cookies.length > 0 ? { Cookie: formatCookieHeader(options.cookies) } : {}
947
+ },
948
+ method: "GET",
949
+ redirect: "follow",
950
+ signal: controller.signal
951
+ });
952
+ if (!response.ok) {
953
+ await response.body?.cancel().catch(() => void 0);
954
+ return null;
955
+ }
956
+ const html = await response.text();
957
+ if (!html.trim()) return null;
958
+ const finalUrl = normalizeResponseUrl(response.url, url) ?? url;
959
+ return { finalUrl, html };
960
+ } catch {
961
+ return null;
962
+ } finally {
963
+ clearTimeout(timer);
964
+ }
965
+ }
966
+ async function resolveXiaohongshuShortLinkHttpDetailed(rawUrl, options = {}) {
967
+ const startUrl = assertXiaohongshuUrl(rawUrl);
968
+ if (!isXiaohongshuShortLinkUrl(startUrl)) {
969
+ return { cookies: [], url: isXiaohongshuNoteUrl(startUrl) ? startUrl : null };
970
+ }
971
+ const fetcher = options.fetcher ?? fetch;
972
+ const timeoutMs = options.timeoutMs ?? DEFAULT_RESOLVE_TIMEOUT_MS;
973
+ const fromManual = await followRedirectsManually(startUrl, { fetcher, timeoutMs });
974
+ if (fromManual.url) return fromManual;
975
+ const fromAuto = await followRedirectsAutomatically(startUrl, { fetcher, timeoutMs });
976
+ return {
977
+ cookies: mergeCookies(fromManual.cookies, fromAuto.cookies),
978
+ url: fromAuto.url
979
+ };
980
+ }
981
+ async function followRedirectsManually(startUrl, options) {
982
+ let current = startUrl;
983
+ const cookieJar = /* @__PURE__ */ new Map();
984
+ for (let hop = 0; hop < MAX_REDIRECT_HOPS; hop += 1) {
985
+ if (isXiaohongshuNoteUrl(current)) return { cookies: [...cookieJar.values()], url: current };
986
+ const controller = new AbortController();
987
+ const timer = setTimeout(() => controller.abort(), options.timeoutMs);
988
+ try {
989
+ const response = await options.fetcher(current, {
990
+ headers: {
991
+ ...RESOLVE_HEADERS,
992
+ ...cookieJar.size > 0 ? { Cookie: formatCookieHeader([...cookieJar.values()]) } : {}
993
+ },
994
+ method: "GET",
995
+ redirect: "manual",
996
+ signal: controller.signal
997
+ });
998
+ await response.body?.cancel().catch(() => void 0);
999
+ for (const cookie of readResponseCookies(response, current)) {
1000
+ cookieJar.set(`${cookie.domain}|${cookie.path}|${cookie.name}`, cookie);
1001
+ }
1002
+ const location = response.headers.get("location");
1003
+ if (location) {
1004
+ current = normalizeXiaohongshuUrl(new URL(location, current).toString());
1005
+ if (isXiaohongshuNoteUrl(current)) {
1006
+ await warmNoteUrl(current, cookieJar, options);
1007
+ return { cookies: [...cookieJar.values()], url: current };
1008
+ }
1009
+ continue;
1010
+ }
1011
+ const responseUrl = normalizeResponseUrl(response.url, current);
1012
+ if (responseUrl && isXiaohongshuNoteUrl(responseUrl)) {
1013
+ await warmNoteUrl(responseUrl, cookieJar, options);
1014
+ return { cookies: [...cookieJar.values()], url: responseUrl };
1015
+ }
1016
+ return { cookies: [...cookieJar.values()], url: null };
1017
+ } catch {
1018
+ return { cookies: [...cookieJar.values()], url: null };
1019
+ } finally {
1020
+ clearTimeout(timer);
1021
+ }
1022
+ }
1023
+ return {
1024
+ cookies: [...cookieJar.values()],
1025
+ url: isXiaohongshuNoteUrl(current) ? current : null
1026
+ };
1027
+ }
1028
+ async function followRedirectsAutomatically(startUrl, options) {
1029
+ const controller = new AbortController();
1030
+ const timer = setTimeout(() => controller.abort(), options.timeoutMs);
1031
+ try {
1032
+ const response = await options.fetcher(startUrl, {
1033
+ headers: RESOLVE_HEADERS,
1034
+ method: "GET",
1035
+ redirect: "follow",
1036
+ signal: controller.signal
1037
+ });
1038
+ await response.body?.cancel().catch(() => void 0);
1039
+ const finalUrl = normalizeResponseUrl(response.url, startUrl);
1040
+ return {
1041
+ cookies: readResponseCookies(response, finalUrl ?? startUrl),
1042
+ url: finalUrl && isXiaohongshuNoteUrl(finalUrl) ? finalUrl : null
1043
+ };
1044
+ } catch {
1045
+ return { cookies: [], url: null };
1046
+ } finally {
1047
+ clearTimeout(timer);
1048
+ }
1049
+ }
1050
+ async function warmNoteUrl(noteUrl, cookieJar, options) {
1051
+ const controller = new AbortController();
1052
+ const timer = setTimeout(() => controller.abort(), options.timeoutMs);
1053
+ try {
1054
+ const response = await options.fetcher(noteUrl, {
1055
+ headers: {
1056
+ ...RESOLVE_HEADERS,
1057
+ ...cookieJar.size > 0 ? { Cookie: formatCookieHeader([...cookieJar.values()]) } : {}
1058
+ },
1059
+ method: "GET",
1060
+ redirect: "manual",
1061
+ signal: controller.signal
1062
+ });
1063
+ await response.body?.cancel().catch(() => void 0);
1064
+ for (const cookie of readResponseCookies(response, noteUrl)) {
1065
+ cookieJar.set(`${cookie.domain}|${cookie.path}|${cookie.name}`, cookie);
1066
+ }
1067
+ } catch {
1068
+ } finally {
1069
+ clearTimeout(timer);
1070
+ }
1071
+ }
1072
+ function readResponseCookies(response, pageUrl) {
1073
+ const host = safeHostname(pageUrl);
1074
+ if (!host) return [];
1075
+ const rawCookies = typeof response.headers.getSetCookie === "function" ? response.headers.getSetCookie() : splitSetCookie(response.headers.get("set-cookie"));
1076
+ const out = [];
1077
+ for (const raw of rawCookies) {
1078
+ const parsed = parseSetCookie(raw, host);
1079
+ if (parsed) out.push(parsed);
1080
+ }
1081
+ return out;
1082
+ }
1083
+ function parseSetCookie(raw, fallbackHost) {
1084
+ const parts = raw.split(";").map((part) => part.trim()).filter(Boolean);
1085
+ const [pair, ...attrs] = parts;
1086
+ if (!pair) return null;
1087
+ const eq = pair.indexOf("=");
1088
+ if (eq <= 0) return null;
1089
+ const name = pair.slice(0, eq).trim();
1090
+ const value = pair.slice(eq + 1).trim();
1091
+ if (!name) return null;
1092
+ let domain = fallbackHost;
1093
+ let path = "/";
1094
+ for (const attr of attrs) {
1095
+ const [key, ...rest] = attr.split("=");
1096
+ const attrKey = key?.trim().toLowerCase();
1097
+ const attrValue = rest.join("=").trim();
1098
+ if (attrKey === "domain" && attrValue) domain = attrValue.replace(/^\./, "");
1099
+ if (attrKey === "path" && attrValue) path = attrValue;
1100
+ }
1101
+ return { domain, name, path, value };
1102
+ }
1103
+ function splitSetCookie(header) {
1104
+ if (!header) return [];
1105
+ return header.split(/,(?=\s*[^;=]+=[^;]+)/).map((part) => part.trim()).filter(Boolean);
1106
+ }
1107
+ function formatCookieHeader(cookies) {
1108
+ return cookies.map((cookie) => `${cookie.name}=${cookie.value}`).join("; ");
1109
+ }
1110
+ function mergeCookies(left, right) {
1111
+ const map = /* @__PURE__ */ new Map();
1112
+ for (const cookie of [...left, ...right]) {
1113
+ map.set(`${cookie.domain}|${cookie.path}|${cookie.name}`, cookie);
1114
+ }
1115
+ return [...map.values()];
1116
+ }
1117
+ function normalizeResponseUrl(responseUrl, fallback) {
1118
+ const raw = String(responseUrl ?? "").trim() || fallback;
1119
+ try {
1120
+ return normalizeXiaohongshuUrl(raw);
1121
+ } catch {
1122
+ return null;
1123
+ }
1124
+ }
1125
+ function safeHostname(url) {
1126
+ try {
1127
+ return new URL(url).hostname;
1128
+ } catch {
1129
+ return null;
1130
+ }
1131
+ }
1132
+ function uniqueUrls(values) {
1133
+ const seen = /* @__PURE__ */ new Set();
1134
+ const out = [];
1135
+ for (const value of values) {
1136
+ if (!value || seen.has(value)) continue;
1137
+ seen.add(value);
1138
+ out.push(value);
1139
+ }
1140
+ return out;
1141
+ }
1142
+
1143
+ // ../../packages/clip-engine/src/xiaohongshuToMarkdown/capture.ts
1144
+ var DEFAULT_TIMEOUT_MS2 = 45e3;
1145
+ var DEFAULT_SELECTOR_TIMEOUT_MS = 2e4;
1146
+ var DEFAULT_SETTLE_MS = 1e3;
1147
+ var DEFAULT_CAPTURE_ATTEMPTS = 2;
1148
+ var DEFAULT_RETRY_DELAY_MS = 1500;
1149
+ var DEFAULT_RESOLVE_TIMEOUT_MS2 = 12e3;
1150
+ var MOBILE_RENDER_SIGNAL_TIMEOUT_MS = 1e4;
1151
+ var MOBILE_USER_AGENT = "Mozilla/5.0 (iPhone; CPU iPhone OS 18_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.5 Mobile/15E148 Safari/604.1";
1152
+ var DEFAULT_HEADERS = {
1153
+ Accept: "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
1154
+ "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
1155
+ "Cache-Control": "no-cache",
1156
+ Pragma: "no-cache",
1157
+ Referer: "https://www.xiaohongshu.com/"
1158
+ };
1159
+ var DESKTOP_STATIC_PROFILE = {
1160
+ javaScriptEnabled: false,
1161
+ mode: "desktop_static",
1162
+ viewport: { width: 1365, height: 900 }
1163
+ };
1164
+ var MOBILE_JS_PROFILE = {
1165
+ javaScriptEnabled: true,
1166
+ mode: "mobile_js",
1167
+ mobileRenderSignalTimeoutMs: MOBILE_RENDER_SIGNAL_TIMEOUT_MS,
1168
+ userAgent: MOBILE_USER_AGENT,
1169
+ viewport: { width: 390, height: 844 }
1170
+ };
1171
+ async function captureXiaohongshuHtml(rawUrl, options = {}) {
1172
+ const inputUrl = toXiaohongshuExploreUrl(assertXiaohongshuUrl(rawUrl));
1173
+ assertNotNonNotePage(inputUrl);
1174
+ let browser = null;
1175
+ try {
1176
+ const attempts = Math.max(1, options.captureAttempts ?? DEFAULT_CAPTURE_ATTEMPTS);
1177
+ const retryDelayMs = options.retryDelayMs ?? DEFAULT_RETRY_DELAY_MS;
1178
+ const shouldResolve = options.resolveShortLink !== false;
1179
+ const resolveOptions = {
1180
+ ...options.fetcher ? { fetcher: options.fetcher } : {},
1181
+ timeoutMs: options.resolveTimeoutMs ?? DEFAULT_RESOLVE_TIMEOUT_MS2
1182
+ };
1183
+ const firstResolved = shouldResolve ? await resolveXiaohongshuCaptureUrl(inputUrl, resolveOptions) : { cookies: [], resolved: false, url: inputUrl };
1184
+ if (firstResolved.resolved) {
1185
+ logInfo("xiaohongshu.capture", "shortlink.resolved", {
1186
+ attempt: 0,
1187
+ cookies: firstResolved.cookies.length,
1188
+ from: inputUrl,
1189
+ to: firstResolved.url
1190
+ });
1191
+ }
1192
+ const httpHit = await tryHttpSsrCapture(inputUrl, firstResolved.url, firstResolved.cookies, options);
1193
+ const needsAudioHydration = Boolean(httpHit) && xiaohongshuCaptureNeedsAudioHydration(httpHit?.html ?? "", httpHit?.finalUrl ?? "");
1194
+ if (httpHit && !needsAudioHydration) return httpHit;
1195
+ browser = await launchBrowser(options.launchOptions);
1196
+ if (httpHit && needsAudioHydration) {
1197
+ return await hydrateXiaohongshuAudio(browser, httpHit, options, firstResolved.cookies);
1198
+ }
1199
+ let lastCapture = null;
1200
+ let lastBlock = { blocked: false };
1201
+ let lastResolvedUrl = firstResolved.url;
1202
+ let lastCookies = firstResolved.cookies;
1203
+ for (let attempt = 1; attempt <= attempts; attempt += 1) {
1204
+ const resolved = attempt === 1 ? firstResolved : shouldResolve ? await resolveXiaohongshuCaptureUrl(inputUrl, resolveOptions) : { cookies: [], resolved: false, url: inputUrl };
1205
+ lastResolvedUrl = resolved.url;
1206
+ lastCookies = resolved.cookies;
1207
+ if (attempt > 1 && resolved.resolved) {
1208
+ logInfo("xiaohongshu.capture", "shortlink.resolved", {
1209
+ attempt,
1210
+ cookies: resolved.cookies.length,
1211
+ from: inputUrl,
1212
+ to: resolved.url
1213
+ });
1214
+ }
1215
+ const navigationUrls = buildNavigationCandidates(inputUrl, resolved.url, attempt);
1216
+ const profileOptions = {
1217
+ ...options,
1218
+ // Share/short-link traffic is mobile-oriented even after HTTP expansion.
1219
+ preferMobileFirst: options.preferMobileFirst ?? isXiaohongshuShortLinkUrl(inputUrl)
1220
+ };
1221
+ for (const [candidateIndex, navigationUrl] of navigationUrls.entries()) {
1222
+ const result = await captureWithFallbacks(browser, navigationUrl, profileOptions, resolved.cookies);
1223
+ lastCapture = result.capture;
1224
+ lastBlock = result.block;
1225
+ if (result.capture.selectorFound) {
1226
+ return annotateCapture(
1227
+ await maybeHydrateXiaohongshuAudio(browser, result.capture, options, resolved.cookies),
1228
+ inputUrl,
1229
+ resolved.url
1230
+ );
1231
+ }
1232
+ if (result.block.blocked) {
1233
+ logWarn("xiaohongshu.capture", "capture.blocked", {
1234
+ attempt,
1235
+ mode: result.capture.captureMode,
1236
+ navigationUrl,
1237
+ reason: result.block.reason ?? null
1238
+ });
1239
+ continue;
1240
+ }
1241
+ const hasMoreCandidates = candidateIndex < navigationUrls.length - 1;
1242
+ if (hasMoreCandidates && isXiaohongshuShortLinkUrl(inputUrl)) {
1243
+ logWarn("xiaohongshu.capture", "capture.soft_miss_continue", {
1244
+ attempt,
1245
+ navigationUrl,
1246
+ next: navigationUrls[candidateIndex + 1] ?? null
1247
+ });
1248
+ continue;
1249
+ }
1250
+ return annotateCapture(result.capture, inputUrl, resolved.url);
1251
+ }
1252
+ if (attempt < attempts) {
1253
+ logWarn("xiaohongshu.capture", "capture.retry", {
1254
+ attempt,
1255
+ delayMs: retryDelayMs * attempt,
1256
+ url: inputUrl
1257
+ });
1258
+ await sleep(retryDelayMs * attempt);
1259
+ }
1260
+ }
1261
+ if (lastBlock.blocked) {
1262
+ const blockedHttp = await tryHttpSsrCapture(
1263
+ inputUrl,
1264
+ lastResolvedUrl,
1265
+ lastCookies,
1266
+ options,
1267
+ lastCapture?.captureMode
1268
+ );
1269
+ if (blockedHttp) return blockedHttp;
1270
+ throw new XiaohongshuToMarkdownError("CAPTURE_BLOCKED", `capture blocked: ${lastBlock.reason}`, {
1271
+ attempts,
1272
+ reason: lastBlock.reason,
1273
+ url: inputUrl
1274
+ });
1275
+ }
1276
+ if (lastCapture) return annotateCapture(lastCapture, inputUrl, lastResolvedUrl);
1277
+ throw new XiaohongshuToMarkdownError("CAPTURE_FAILED", "Xiaohongshu capture produced no page", { url: inputUrl });
1278
+ } catch (error) {
1279
+ if (error instanceof XiaohongshuToMarkdownError) throw error;
1280
+ throw new XiaohongshuToMarkdownError("CAPTURE_FAILED", errorMessage(error), { url: inputUrl });
1281
+ } finally {
1282
+ await browser?.close().catch(() => void 0);
1283
+ }
1284
+ }
1285
+ async function captureWithFallbacks(browser, navigationUrl, options, resolveCookies = []) {
1286
+ const preferMobile = isXiaohongshuShortLinkUrl(navigationUrl) || options.preferMobileFirst === true;
1287
+ const profiles = preferMobile ? [MOBILE_JS_PROFILE, DESKTOP_STATIC_PROFILE] : [DESKTOP_STATIC_PROFILE, MOBILE_JS_PROFILE];
1288
+ const enabledProfiles = options.mobileJsFallback === false ? profiles.slice(0, 1) : profiles;
1289
+ let previous = null;
1290
+ for (const [index, profile] of enabledProfiles.entries()) {
1291
+ const capture = await captureWithProfile(browser, navigationUrl, options, profile, resolveCookies);
1292
+ if (capture.selectorFound) {
1293
+ return { block: { blocked: false }, capture: withFallbackFrom(capture, previous) };
1294
+ }
1295
+ const block = readCaptureBlock(capture);
1296
+ const isLast = index === enabledProfiles.length - 1;
1297
+ if (!isLast) {
1298
+ previous = capture;
1299
+ continue;
1300
+ }
1301
+ return { block, capture: withFallbackFrom(capture, previous) };
1302
+ }
1303
+ throw new XiaohongshuToMarkdownError("CAPTURE_FAILED", "Xiaohongshu capture produced no profile result", {
1304
+ url: navigationUrl
1305
+ });
1306
+ }
1307
+ async function captureWithProfile(browser, url, options, profile, resolveCookies = []) {
1308
+ let context = null;
1309
+ try {
1310
+ context = await browser.newContext({
1311
+ extraHTTPHeaders: {
1312
+ ...DEFAULT_HEADERS,
1313
+ ...options.headers ?? {}
1314
+ },
1315
+ javaScriptEnabled: profile.javaScriptEnabled,
1316
+ locale: "zh-CN",
1317
+ ...profile.userAgent ? { userAgent: profile.userAgent } : {},
1318
+ viewport: profile.viewport
1319
+ });
1320
+ if (resolveCookies.length > 0) {
1321
+ await context.addCookies(
1322
+ resolveCookies.map((cookie) => {
1323
+ const host = cookie.domain.replace(/^\./, "");
1324
+ return {
1325
+ domain: host.includes(".") ? `.${host}` : host,
1326
+ name: cookie.name,
1327
+ path: cookie.path || "/",
1328
+ value: cookie.value
1329
+ };
1330
+ })
1331
+ );
1332
+ }
1333
+ if (profile.mobileRenderSignalTimeoutMs) await blockXiaohongshuOpenAppRedirects(context);
1334
+ const page = await context.newPage();
1335
+ await page.goto(url, {
1336
+ timeout: options.timeoutMs ?? DEFAULT_TIMEOUT_MS2,
1337
+ waitUntil: options.waitUntil ?? "domcontentloaded"
1338
+ });
1339
+ const landedUrl = page.url();
1340
+ if (isXiaohongshuShortLinkUrl(url) && isXiaohongshuNoteUrl(landedUrl)) {
1341
+ logInfo("xiaohongshu.capture", "shortlink.browser_expanded", {
1342
+ from: url,
1343
+ to: landedUrl
1344
+ });
1345
+ }
1346
+ const selectorFound = await waitForCaptureSignal(
1347
+ page,
1348
+ options.selectorTimeoutMs ?? DEFAULT_SELECTOR_TIMEOUT_MS,
1349
+ profile
1350
+ );
1351
+ const settleMs = options.settleMs ?? DEFAULT_SETTLE_MS;
1352
+ if (settleMs > 0) await page.waitForTimeout(settleMs);
1353
+ const html = await injectLiveAudioIntoHtml(page, await page.content());
1354
+ const title = await page.title().catch(() => "");
1355
+ return {
1356
+ capturedAt: (/* @__PURE__ */ new Date()).toISOString(),
1357
+ captureMode: profile.mode,
1358
+ finalUrl: landedUrl,
1359
+ html,
1360
+ selectorFound,
1361
+ title,
1362
+ url
1363
+ };
1364
+ } finally {
1365
+ await context?.close().catch(() => void 0);
1366
+ }
1367
+ }
1368
+ async function blockXiaohongshuOpenAppRedirects(context) {
1369
+ await context.route("**/*", async (route) => {
1370
+ const requestUrl = route.request().url();
1371
+ if (requestUrl.includes("://oia.xiaohongshu.com/") || requestUrl.includes("/oia?")) {
1372
+ await route.abort();
1373
+ return;
1374
+ }
1375
+ await route.continue();
1376
+ });
1377
+ }
1378
+ async function waitForCaptureSignal(page, selectorTimeoutMs, profile) {
1379
+ if (!profile.mobileRenderSignalTimeoutMs) return await waitForXiaohongshuContent(page, selectorTimeoutMs);
1380
+ const selector = waitForXiaohongshuContent(page, profile.mobileRenderSignalTimeoutMs);
1381
+ const mobile = waitForMobileRenderedSignal(page, profile.mobileRenderSignalTimeoutMs).then(() => false);
1382
+ return await Promise.race([selector, mobile]);
1383
+ }
1384
+ async function waitForXiaohongshuContent(page, timeoutMs) {
1385
+ try {
1386
+ await page.waitForSelector("#detail-desc, #detail-title, .note-content, .note-container, #note-container", {
1387
+ timeout: timeoutMs
1388
+ });
1389
+ return true;
1390
+ } catch {
1391
+ return false;
1392
+ }
1393
+ }
1394
+ async function waitForMobileRenderedSignal(page, timeoutMs) {
1395
+ try {
1396
+ await page.waitForFunction(
1397
+ `(() => {
1398
+ const title = document.title.trim()
1399
+ if (title && title !== '\u5C0F\u7EA2\u4E66' && !title.includes('\u4F60\u8BBF\u95EE\u7684\u9875\u9762\u4E0D\u89C1\u4E86')) return true
1400
+ const html = document.documentElement.innerHTML
1401
+ return Boolean(
1402
+ document.querySelector('img[src*="xhscdn.com"], img[src*="xiaohongshu.com"]') ??
1403
+ ((html.includes('sns-webpic-') || html.includes('sns-video-') || html.includes('sns-avatar-')) &&
1404
+ html.includes('xhscdn.com')),
1405
+ )
1406
+ })()`,
1407
+ void 0,
1408
+ { timeout: timeoutMs }
1409
+ );
1410
+ return true;
1411
+ } catch {
1412
+ return false;
1413
+ }
1414
+ }
1415
+ function buildNavigationCandidates(inputUrl, resolvedUrl, attempt) {
1416
+ const urls = [resolvedUrl];
1417
+ if (isXiaohongshuShortLinkUrl(inputUrl)) {
1418
+ if (resolvedUrl !== inputUrl) urls.push(inputUrl);
1419
+ if (attempt > 1) {
1420
+ const alternate = alternateXiaohongshuShortLinkUrl(inputUrl);
1421
+ if (alternate) urls.push(alternate);
1422
+ }
1423
+ } else if (resolvedUrl !== inputUrl) {
1424
+ urls.push(inputUrl);
1425
+ }
1426
+ return uniquePreserveOrder(urls);
1427
+ }
1428
+ function annotateCapture(capture, inputUrl, resolvedUrl) {
1429
+ return {
1430
+ ...capture,
1431
+ url: inputUrl,
1432
+ ...resolvedUrl !== inputUrl && isXiaohongshuNoteUrl(resolvedUrl) ? { resolvedUrl } : {}
1433
+ };
1434
+ }
1435
+ function withFallbackFrom(capture, previous) {
1436
+ if (!previous || previous.captureMode === capture.captureMode) return capture;
1437
+ return { ...capture, fallbackFrom: previous.captureMode };
1438
+ }
1439
+ function assertNotNonNotePage(url) {
1440
+ const kind = xiaohongshuNonNotePageKind(url);
1441
+ if (kind) {
1442
+ throw new XiaohongshuToMarkdownError("UNSUPPORTED_CONTENT_TYPE", `xiaohongshu link opens a ${kind}, not a single note`, {
1443
+ url
1444
+ });
1445
+ }
1446
+ }
1447
+ function readCaptureBlock(capture) {
1448
+ if (capture.selectorFound) return { blocked: false };
1449
+ if (hasParseableXiaohongshuNote(capture.html, capture.finalUrl || capture.url)) {
1450
+ return { blocked: false };
1451
+ }
1452
+ return detectCaptureBlock({ html: capture.html, title: capture.title, url: capture.finalUrl });
1453
+ }
1454
+ async function tryHttpSsrCapture(inputUrl, candidateUrl, cookies, options, fallbackFrom) {
1455
+ if (options.httpSsrFallback === false) return null;
1456
+ const noteUrl = isXiaohongshuNoteUrl(candidateUrl) ? candidateUrl : isXiaohongshuNoteUrl(inputUrl) ? inputUrl : "";
1457
+ if (!noteUrl) return null;
1458
+ const fetched = await fetchXiaohongshuPageHtml(noteUrl, {
1459
+ cookies,
1460
+ ...options.fetcher ? { fetcher: options.fetcher } : {},
1461
+ timeoutMs: options.resolveTimeoutMs ?? DEFAULT_RESOLVE_TIMEOUT_MS2
1462
+ });
1463
+ if (!fetched) return null;
1464
+ const finalUrl = isXiaohongshuNoteUrl(fetched.finalUrl) ? fetched.finalUrl : noteUrl;
1465
+ if (!hasParseableXiaohongshuNote(fetched.html, finalUrl)) return null;
1466
+ const title = fetched.html.match(/<title[^>]*>([^<]*)<\/title>/i)?.[1]?.trim() ?? "";
1467
+ logInfo("xiaohongshu.capture", "http_ssr.hit", {
1468
+ fallbackFrom: fallbackFrom ?? null,
1469
+ from: inputUrl,
1470
+ to: finalUrl
1471
+ });
1472
+ return annotateCapture(
1473
+ {
1474
+ capturedAt: (/* @__PURE__ */ new Date()).toISOString(),
1475
+ captureMode: "http_ssr",
1476
+ ...fallbackFrom ? { fallbackFrom } : {},
1477
+ finalUrl,
1478
+ html: fetched.html,
1479
+ selectorFound: true,
1480
+ title,
1481
+ url: inputUrl
1482
+ },
1483
+ inputUrl,
1484
+ finalUrl
1485
+ );
1486
+ }
1487
+ async function maybeHydrateXiaohongshuAudio(browser, capture, options, cookies) {
1488
+ if (!xiaohongshuCaptureNeedsAudioHydration(capture.html, capture.finalUrl || capture.url)) {
1489
+ return capture;
1490
+ }
1491
+ return await hydrateXiaohongshuAudio(browser, capture, options, cookies);
1492
+ }
1493
+ async function hydrateXiaohongshuAudio(browser, capture, options, cookies) {
1494
+ const noteUrl = isXiaohongshuNoteUrl(capture.finalUrl) ? capture.finalUrl : isXiaohongshuNoteUrl(capture.url) ? capture.url : "";
1495
+ if (!noteUrl) return capture;
1496
+ let context = null;
1497
+ try {
1498
+ context = await browser.newContext({
1499
+ extraHTTPHeaders: {
1500
+ ...DEFAULT_HEADERS,
1501
+ ...options.headers ?? {}
1502
+ },
1503
+ javaScriptEnabled: true,
1504
+ locale: "zh-CN",
1505
+ viewport: { width: 1365, height: 900 }
1506
+ });
1507
+ if (cookies.length > 0) {
1508
+ await context.addCookies(
1509
+ cookies.map((cookie) => {
1510
+ const host = cookie.domain.replace(/^\./, "");
1511
+ return {
1512
+ domain: host.includes(".") ? `.${host}` : host,
1513
+ name: cookie.name,
1514
+ path: cookie.path || "/",
1515
+ value: cookie.value
1516
+ };
1517
+ })
1518
+ );
1519
+ }
1520
+ const page = await context.newPage();
1521
+ const fromNetwork = [];
1522
+ page.on("response", (response) => {
1523
+ const responseUrl = response.url();
1524
+ if (!/\/api\/sns\/[^?]*(?:feed|note_info|widgets)/i.test(responseUrl)) return;
1525
+ void response.json().then((json) => {
1526
+ fromNetwork.push(json);
1527
+ }).catch(() => void 0);
1528
+ });
1529
+ const exploreUrl = toXiaohongshuExploreUrl(noteUrl);
1530
+ await page.goto(exploreUrl, {
1531
+ timeout: options.timeoutMs ?? DEFAULT_TIMEOUT_MS2,
1532
+ waitUntil: options.waitUntil ?? "domcontentloaded"
1533
+ });
1534
+ await waitForXiaohongshuContent(page, options.selectorTimeoutMs ?? DEFAULT_SELECTOR_TIMEOUT_MS);
1535
+ const settleMs = options.settleMs ?? DEFAULT_SETTLE_MS;
1536
+ if (settleMs > 0) await page.waitForTimeout(settleMs);
1537
+ const audio = await readLiveXiaohongshuAudio(page) ?? collectXiaohongshuAudioFromUnknown(fromNetwork)[0];
1538
+ if (!audio?.url) {
1539
+ logWarn("xiaohongshu.capture", "audio.hydrate.miss", { url: exploreUrl });
1540
+ return capture;
1541
+ }
1542
+ logInfo("xiaohongshu.capture", "audio.hydrate.hit", {
1543
+ durationSeconds: audio.durationSeconds ?? null,
1544
+ from: capture.captureMode,
1545
+ url: exploreUrl
1546
+ });
1547
+ return { ...capture, html: injectXiaohongshuClipAudio(capture.html, audio) };
1548
+ } catch (error) {
1549
+ logWarn("xiaohongshu.capture", "audio.hydrate.failed", {
1550
+ message: errorMessage(error),
1551
+ url: noteUrl
1552
+ });
1553
+ return capture;
1554
+ } finally {
1555
+ await context?.close().catch(() => void 0);
1556
+ }
1557
+ }
1558
+ async function injectLiveAudioIntoHtml(page, html) {
1559
+ const audio = await readLiveXiaohongshuAudio(page);
1560
+ return audio?.url ? injectXiaohongshuClipAudio(html, audio) : html;
1561
+ }
1562
+ async function readLiveXiaohongshuAudio(page) {
1563
+ try {
1564
+ const state = await page.evaluate(`(() => {
1565
+ const root = window.__INITIAL_STATE__
1566
+ if (!root || typeof root !== 'object') return null
1567
+ const notes = []
1568
+ const noteStore = root.note
1569
+ const detailMap = noteStore && noteStore.noteDetailMap
1570
+ if (detailMap && typeof detailMap === 'object') {
1571
+ for (const entry of Object.values(detailMap)) {
1572
+ if (entry && typeof entry === 'object' && entry.note) notes.push(entry.note)
1573
+ }
1574
+ }
1575
+ const noteData = root.noteData && root.noteData.data && root.noteData.data.noteData
1576
+ if (noteData) notes.push(noteData)
1577
+ const preload = root.noteData && root.noteData.normalNotePreloadData
1578
+ if (preload) notes.push(preload)
1579
+ for (const note of notes) {
1580
+ if (note && note.audioInfo) return note.audioInfo
1581
+ }
1582
+ return null
1583
+ })()`);
1584
+ const audio = collectXiaohongshuAudioFromUnknown({ audioInfo: state })[0];
1585
+ return audio ?? null;
1586
+ } catch {
1587
+ return null;
1588
+ }
1589
+ }
1590
+ function uniquePreserveOrder(values) {
1591
+ const seen = /* @__PURE__ */ new Set();
1592
+ const out = [];
1593
+ for (const value of values) {
1594
+ if (seen.has(value)) continue;
1595
+ seen.add(value);
1596
+ out.push(value);
1597
+ }
1598
+ return out;
1599
+ }
1600
+ function sleep(ms) {
1601
+ return new Promise((resolve) => setTimeout(resolve, ms));
1602
+ }
1603
+ function errorMessage(error) {
1604
+ return error instanceof Error ? error.message : String(error);
1605
+ }
1606
+
1607
+ // ../../packages/clip-engine/src/xiaohongshuToMarkdown/markdown.ts
1608
+ import TurndownService from "turndown";
1609
+ import { gfm } from "turndown-plugin-gfm";
1610
+ function convertXiaohongshuHtmlToMarkdown(contentHtml, media = []) {
1611
+ const service = new TurndownService({
1612
+ bulletListMarker: "-",
1613
+ codeBlockStyle: "fenced",
1614
+ emDelimiter: "*",
1615
+ headingStyle: "atx"
1616
+ });
1617
+ service.use(gfm);
1618
+ service.addRule("videoLink", {
1619
+ filter: "video",
1620
+ replacement: (_content, node) => {
1621
+ const src = node.getAttribute?.("src");
1622
+ return src ? `
1623
+
1624
+ [\u89C6\u9891](${src})
1625
+
1626
+ ` : "";
1627
+ }
1628
+ });
1629
+ const mediaHtml = buildTopMediaHtml(media);
1630
+ return service.turndown(`${mediaHtml}${contentHtml}`).replace(/\u00a0/g, " ").replace(/\n{4,}/g, "\n\n\n").replace(/[ \t]+$/gm, "").trim();
1631
+ }
1632
+ function replaceXiaohongshuMarkdownMediaUrls(markdown, urlMap) {
1633
+ let rewritten = markdown;
1634
+ for (const [remoteUrl, localPath] of urlMap.entries()) {
1635
+ rewritten = rewritten.replaceAll(remoteUrl, escapeMarkdownDestination(localPath));
1636
+ }
1637
+ return rewritten;
1638
+ }
1639
+ function buildXiaohongshuMarkdown(metadata, bodyMarkdown) {
1640
+ return composeClipMarkdown(bodyMarkdown, {
1641
+ site: "Xiaohongshu",
1642
+ sourceUrl: metadata.sourceUrl,
1643
+ author: metadata.author,
1644
+ publishTime: metadata.publishTime
1645
+ });
1646
+ }
1647
+ function buildTopMediaHtml(media) {
1648
+ return orderTopMedia(media).map((item) => {
1649
+ const src = escapeHtmlAttribute(item.url);
1650
+ if (item.type === "video") return `<video controls src="${src}"></video>`;
1651
+ return `<img src="${src}" alt="\u56FE\u7247">`;
1652
+ }).join("\n");
1653
+ }
1654
+ function orderTopMedia(media) {
1655
+ const images = media.filter((item) => item.type === "image");
1656
+ const videos = media.filter((item) => item.type === "video");
1657
+ return [...images, ...videos];
1658
+ }
1659
+ function escapeMarkdownDestination(value) {
1660
+ return value.replace(/ /g, "%20").replace(/\(/g, "\\(").replace(/\)/g, "\\)");
1661
+ }
1662
+ function escapeHtmlAttribute(value) {
1663
+ return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
1664
+ }
1665
+
1666
+ // ../../packages/clip-engine/src/clip/xiaohongshu.ts
1667
+ async function extractXiaohongshuClip(url, ctx) {
1668
+ const { captureTimeoutMs, media } = clipEngineConfig();
1669
+ logInfo("xiaohongshu.runner", "run.start", {
1670
+ timeoutMs: captureTimeoutMs,
1671
+ url,
1672
+ workDir: ctx.workDir
1673
+ });
1674
+ const capture = await captureXiaohongshuHtml(url, { timeoutMs: captureTimeoutMs });
1675
+ logInfo("xiaohongshu.runner", "capture.done", {
1676
+ captureMode: capture.captureMode,
1677
+ fallbackFrom: capture.fallbackFrom ?? null,
1678
+ finalUrl: capture.finalUrl,
1679
+ resolvedUrl: capture.resolvedUrl ?? null,
1680
+ selectorFound: capture.selectorFound,
1681
+ title: capture.title
1682
+ });
1683
+ const parsed = parseCaptureOrClassifyBlock(capture);
1684
+ const images = parsed.media.filter(isXiaohongshuImage);
1685
+ const videos = parsed.media.filter(isXiaohongshuVideo);
1686
+ const audios = parsed.media.filter(isXiaohongshuAudio);
1687
+ const imageAssets = await downloadXiaohongshuMedia({
1688
+ concurrency: media.imageConcurrency,
1689
+ maxBytes: media.maxImageBytes,
1690
+ media: images,
1691
+ mediaDir: ctx.workDir,
1692
+ mediaTypes: ["image"],
1693
+ retries: media.downloadRetries
1694
+ });
1695
+ if (imageAssets.failed.length > 0) {
1696
+ logWarn("xiaohongshu.runner", "image.download.partial", {
1697
+ downloaded: imageAssets.downloaded.length,
1698
+ failed: imageAssets.failed.length,
1699
+ ...summarizeImageFailures(imageAssets.failed)
1700
+ });
1701
+ }
1702
+ const bodyMarkdown = convertXiaohongshuHtmlToMarkdown(parsed.contentHtml, images);
1703
+ const document = {
1704
+ author: parsed.metadata.author,
1705
+ markdown: buildXiaohongshuMarkdown(
1706
+ parsed.metadata,
1707
+ replaceXiaohongshuMarkdownMediaUrls(bodyMarkdown, imageAssets.urlMap)
1708
+ ),
1709
+ publishTime: parsed.metadata.publishTime,
1710
+ rawMarkdown: buildXiaohongshuMarkdown(parsed.metadata, bodyMarkdown),
1711
+ sourceUrl: parsed.metadata.sourceUrl,
1712
+ title: parsed.metadata.title
1713
+ };
1714
+ const primary = await downloadPrimaryMedia(ctx.workDir, audios, videos);
1715
+ if (primary) document.primaryMedia = primary;
1716
+ logInfo("xiaohongshu.runner", "extract.ok", {
1717
+ captureMode: capture.captureMode,
1718
+ fallbackFrom: capture.fallbackFrom ?? null,
1719
+ images: imageAssets.downloaded.length,
1720
+ primaryAudio: primary?.type === "audio",
1721
+ primaryVideo: primary?.type === "video",
1722
+ title: parsed.metadata.title
1723
+ });
1724
+ return document;
1725
+ }
1726
+ function parseCaptureOrClassifyBlock(capture) {
1727
+ try {
1728
+ return parseXiaohongshuHtml(capture.html, {
1729
+ sourceUrl: capture.finalUrl || capture.url
1730
+ });
1731
+ } catch (error) {
1732
+ if (error instanceof XiaohongshuToMarkdownError && error.code === "CONTENT_NOT_FOUND" && !capture.selectorFound) {
1733
+ throw new XiaohongshuToMarkdownError(
1734
+ "CAPTURE_BLOCKED",
1735
+ "Xiaohongshu note content unavailable \u2014 likely anti-bot interception or an expired share link",
1736
+ {
1737
+ captureMode: capture.captureMode,
1738
+ finalUrl: capture.finalUrl,
1739
+ url: capture.url
1740
+ }
1741
+ );
1742
+ }
1743
+ throw error;
1744
+ }
1745
+ }
1746
+ function isXiaohongshuImage(item) {
1747
+ return item.type === "image";
1748
+ }
1749
+ function isXiaohongshuVideo(item) {
1750
+ return item.type === "video";
1751
+ }
1752
+ function isXiaohongshuAudio(item) {
1753
+ return item.type === "audio";
1754
+ }
1755
+ async function downloadPrimaryMedia(workDir, audios, videos) {
1756
+ const primaryAudio = await downloadPrimaryAudio(workDir, audios);
1757
+ if (primaryAudio) return primaryAudio;
1758
+ return await downloadPrimaryVideo(workDir, videos) ?? void 0;
1759
+ }
1760
+ async function downloadPrimaryAudio(workDir, audios) {
1761
+ const primary = audios[0];
1762
+ if (!primary) return null;
1763
+ const { captureTimeoutMs, media } = clipEngineConfig();
1764
+ try {
1765
+ const audioAssets = await downloadXiaohongshuMedia({
1766
+ maxBytes: media.maxVideoBytes,
1767
+ media: [primary],
1768
+ mediaDir: workDir,
1769
+ mediaTypes: ["audio"],
1770
+ retries: media.downloadRetries,
1771
+ timeoutMs: Math.max(6e4, captureTimeoutMs)
1772
+ });
1773
+ if (audioAssets.failed.length > 0) {
1774
+ logWarn("xiaohongshu.runner", "audio.download.failed", {
1775
+ message: audioAssets.failed[0]?.message ?? "unknown error",
1776
+ url: primary.url
1777
+ });
1778
+ return null;
1779
+ }
1780
+ const audio = audioAssets.downloaded[0];
1781
+ if (!audio || audio.type !== "audio") {
1782
+ logWarn("xiaohongshu.runner", "audio.missing", { url: primary.url });
1783
+ return null;
1784
+ }
1785
+ return {
1786
+ bytes: audio.bytes,
1787
+ contentType: audio.contentType,
1788
+ localPath: audio.localPath,
1789
+ remoteUrl: audio.remoteUrl,
1790
+ type: "audio",
1791
+ ...audio.durationSeconds ? { durationSeconds: audio.durationSeconds } : {}
1792
+ };
1793
+ } catch (error) {
1794
+ logWarn("xiaohongshu.runner", "audio.download.failed", {
1795
+ message: error instanceof Error ? error.message : String(error),
1796
+ url: primary.url
1797
+ });
1798
+ return null;
1799
+ }
1800
+ }
1801
+ async function downloadPrimaryVideo(workDir, videos) {
1802
+ const primary = videos[0];
1803
+ if (!primary) return null;
1804
+ const { media } = clipEngineConfig();
1805
+ const { download, failures } = await downloadXiaohongshuVideoWithFallback({
1806
+ maxBytes: media.maxVideoBytes,
1807
+ mediaDir: workDir,
1808
+ onFallback: (failure, nextUrl) => {
1809
+ logWarn("xiaohongshu.runner", "video.download.fallback", {
1810
+ failedUrl: failure.remoteUrl,
1811
+ message: failure.message,
1812
+ nextUrl
1813
+ });
1814
+ },
1815
+ retries: media.downloadRetries,
1816
+ video: primary
1817
+ });
1818
+ if (!download) {
1819
+ const suffix = failures.length > 1 ? ` (tried ${failures.length} sources)` : "";
1820
+ throw new Error(`primary video download failed: ${failures[0]?.message ?? "unknown error"}${suffix}`);
1821
+ }
1822
+ if (download.type !== "video") throw new Error("primary video download did not produce a file");
1823
+ if (failures.length > 0) {
1824
+ logInfo("xiaohongshu.runner", "video.download.fallback_succeeded", {
1825
+ attempts: failures.length + 1,
1826
+ url: download.remoteUrl
1827
+ });
1828
+ }
1829
+ return { ...download, type: "video" };
1830
+ }
1831
+ export {
1832
+ extractXiaohongshuClip
1833
+ };