hyperframes 0.9.55 → 0.9.58

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 (410) hide show
  1. package/dist/{add-2LZ5XA27.js → add-JQUKPSEZ.js} +30 -28
  2. package/dist/{agentPromptGenerator-RSFEFNFL.js → agentPromptGenerator-3NEY7FPP.js} +16 -15
  3. package/dist/{animatedGifPrep-AX4MK2QD.js → animatedGifPrep-VMUZ6IVJ.js} +18 -16
  4. package/dist/api.js +61 -59
  5. package/dist/{appHistory-T3ZLA7QN.js → appHistory-JNI6IOR6.js} +7 -4
  6. package/dist/{asset-XYQJVHR2.js → asset-ZT3VXZ67.js} +3 -2
  7. package/dist/{assetCataloger-WTFR2Z5Q.js → assetCataloger-D2DV65BA.js} +17 -16
  8. package/dist/{audio-U2OIHTUI.js → audio-LD5H2R5V.js} +40 -39
  9. package/dist/{auth-DXESNULL.js → auth-4FPYYMSH.js} +4 -4
  10. package/dist/{autoUpdate-DWT4YYU2.js → autoUpdate-5ZKSFCG4.js} +5 -5
  11. package/dist/{avatars-EL5RBI4P.js → avatars-DCLFE7VG.js} +26 -24
  12. package/dist/{backgroundChecks-T2DL425O.js → backgroundChecks-UZA3F46H.js} +6 -6
  13. package/dist/backgroundChecksWorker.js +6 -6
  14. package/dist/{batchRender-CMG4SVBX.js → batchRender-TAUW3CT2.js} +14 -9
  15. package/dist/{beats-HU756KUO.js → beats-X3LCR6OG.js} +16 -15
  16. package/dist/{benchmark-HBNCPXH5.js → benchmark-DNZQT3YQ.js} +23 -22
  17. package/dist/{billing-LGHM3LC7.js → billing-4BFUAHWX.js} +44 -29
  18. package/dist/{browser-XIFUT5OB.js → browser-5J2MTDB6.js} +14 -13
  19. package/dist/{bundleWithLocalizedFonts-JPPBCCVV.js → bundleWithLocalizedFonts-XWK47ZVF.js} +1 -1
  20. package/dist/{capture-ZY7G3QSM.js → capture-2YSVFKWV.js} +40 -39
  21. package/dist/{capture-B6DSZD2P.js → capture-TVYTKWTG.js} +4 -4
  22. package/dist/{captureCompositionFrame-2WRG6SNW.js → captureCompositionFrame-L765HLCT.js} +22 -21
  23. package/dist/{captureFile-LXMDM5TD.js → captureFile-DOCK42K3.js} +4 -3
  24. package/dist/{catalog-CUEOQ4PJ.js → catalog-CHGGRRQX.js} +30 -28
  25. package/dist/catalog-artifact/media-vectors.json +205 -0
  26. package/dist/{catch-up-BAYJTXAL.js → catch-up-OCFU6ZR3.js} +18 -17
  27. package/dist/{check-KGXBQPRZ.js → check-LWK4Z7FI.js} +66 -63
  28. package/dist/{checkAudio-6PI7DJLP.js → checkAudio-R5ORBXBO.js} +27 -24
  29. package/dist/{checkBrowser-4SGXUL27.js → checkBrowser-6SH73T47.js} +56 -55
  30. package/dist/{chunk-VK3MQSA2.js → chunk-23SG3B6M.js} +5 -2
  31. package/dist/{chunk-EXXIFMUX.js → chunk-2GRCLLKU.js} +13 -5
  32. package/dist/chunk-2RUCE54M.js +5083 -0
  33. package/dist/{chunk-PLFOZIEH.js → chunk-2SJNGWSY.js} +1 -1
  34. package/dist/{chunk-FPRHOB5W.js → chunk-2WA62M3B.js} +3 -3
  35. package/dist/{chunk-E2DHBP6C.js → chunk-37VS6QY6.js} +1 -1
  36. package/dist/{chunk-KG24ATFM.js → chunk-37Y334MN.js} +13 -11
  37. package/dist/{chunk-ER22SVLT.js → chunk-3GKGBYW3.js} +7 -27
  38. package/dist/{chunk-SDFGDNWV.js → chunk-3VMZQQUI.js} +1 -1
  39. package/dist/{chunk-NUGAYGT3.js → chunk-4LZSNWFJ.js} +2 -2
  40. package/dist/{chunk-JVA3SAGB.js → chunk-4N3WOFP3.js} +30 -37
  41. package/dist/{chunk-W2GXQ3CR.js → chunk-4NNYYCJN.js} +15 -15
  42. package/dist/{chunk-TMLKMCZK.js → chunk-4QPT3IEL.js} +5 -5
  43. package/dist/{chunk-3L2POG2J.js → chunk-5IE5ZI66.js} +37 -8
  44. package/dist/{chunk-4IUOWNDS.js → chunk-5IUVWP3A.js} +2 -2
  45. package/dist/{chunk-3USMIMBB.js → chunk-5SGGOZNL.js} +464 -140
  46. package/dist/chunk-677JGYQL.js +91 -0
  47. package/dist/{chunk-LEIR7IDJ.js → chunk-6LU6JICP.js} +80 -1
  48. package/dist/{chunk-QWBJABCA.js → chunk-7ECPFKQV.js} +4 -4
  49. package/dist/{chunk-BZULWFMJ.js → chunk-7FIJRDUG.js} +45 -10
  50. package/dist/{chunk-VCKUDUPN.js → chunk-7IMHPBSH.js} +248 -32
  51. package/dist/{chunk-OM2WIZOR.js → chunk-7WAWUQDQ.js} +3 -3
  52. package/dist/{chunk-F7B2YDPM.js → chunk-7WYJXKIG.js} +19 -11
  53. package/dist/{chunk-OWQWMQTY.js → chunk-7ZHBY7T5.js} +1 -1
  54. package/dist/{chunk-GKOF2RS3.js → chunk-A4L7G74T.js} +1 -1
  55. package/dist/{chunk-NHNFBLBM.js → chunk-A4YRESMH.js} +6 -3
  56. package/dist/{chunk-MDRLJ737.js → chunk-AJ7YRQS4.js} +1 -1
  57. package/dist/{chunk-WPD7JH6F.js → chunk-ALD7JBPV.js} +2 -2
  58. package/dist/{chunk-5HJZGP54.js → chunk-AM4Y3XMR.js} +2 -2
  59. package/dist/{chunk-7DJCG5ED.js → chunk-AM6UYKVR.js} +10 -10
  60. package/dist/{chunk-FOKS5HQ2.js → chunk-AMS7Q7P7.js} +4 -4
  61. package/dist/{chunk-EKZ5FGV7.js → chunk-BSDUTNFX.js} +1 -1
  62. package/dist/{chunk-6BGTTCKN.js → chunk-BSFTB6AM.js} +5 -5
  63. package/dist/{chunk-NCSBBZQ5.js → chunk-CGJIMWNU.js} +5 -2
  64. package/dist/{chunk-TULCSCC4.js → chunk-CGODFJZ7.js} +9 -9
  65. package/dist/{chunk-JS7UI73E.js → chunk-CPDPSNSB.js} +8 -8
  66. package/dist/{chunk-NMQCIUBE.js → chunk-CRPLPK6J.js} +10 -8
  67. package/dist/{chunk-PPLFDG7N.js → chunk-CVTIGS5K.js} +3 -3
  68. package/dist/{chunk-NKAW4RVE.js → chunk-D2LSYXLW.js} +1 -1
  69. package/dist/{chunk-CHQWDBUM.js → chunk-D3M5VOC5.js} +9 -14
  70. package/dist/{chunk-TPLO6NJI.js → chunk-DH3M5X3Y.js} +4 -4
  71. package/dist/{chunk-WQGQCSRY.js → chunk-DHVRVI7F.js} +5 -5
  72. package/dist/{chunk-KCF6Q54R.js → chunk-DL6PEJWH.js} +5 -2
  73. package/dist/{chunk-LGYCWN3Q.js → chunk-DWFWF6IR.js} +30 -22
  74. package/dist/{chunk-KVYHRUZX.js → chunk-DX5Y3L5B.js} +3 -3
  75. package/dist/{chunk-T5S7U5C6.js → chunk-E26Z73S3.js} +1 -1
  76. package/dist/{chunk-OTWFSHYH.js → chunk-E4IR34CF.js} +434 -306
  77. package/dist/{chunk-32IRBM3V.js → chunk-ELRE6LVJ.js} +3 -3
  78. package/dist/{chunk-EUJSQHIL.js → chunk-EOXNEA4Z.js} +2 -2
  79. package/dist/{chunk-QGQYMSYM.js → chunk-ERDQIRUL.js} +4 -4
  80. package/dist/{chunk-ATKA5KHE.js → chunk-EWKJDXH6.js} +3 -3
  81. package/dist/{chunk-FLHL32SV.js → chunk-EZJHKHWU.js} +36 -8
  82. package/dist/{chunk-QQLVSUO7.js → chunk-FFOFGL2O.js} +2 -2
  83. package/dist/{chunk-UHVKV5IF.js → chunk-FNXU56VT.js} +1 -1
  84. package/dist/{chunk-BMJGWQ5X.js → chunk-G3U5CUF3.js} +1 -1
  85. package/dist/{chunk-ON3CGL3V.js → chunk-GDIBE57N.js} +2 -2
  86. package/dist/{chunk-MWTOYGIJ.js → chunk-GEOJA37C.js} +3 -3
  87. package/dist/{chunk-MO5NTFSC.js → chunk-GIVMQDSK.js} +2 -2
  88. package/dist/{chunk-UCLUH5AG.js → chunk-GRSZAGJB.js} +2 -2
  89. package/dist/{chunk-AGTBMLNM.js → chunk-GVIJFPZV.js} +2 -2
  90. package/dist/{chunk-YVCPUVHV.js → chunk-H3LEOZVK.js} +1 -1
  91. package/dist/{chunk-OAV5ESA6.js → chunk-H7DTMLAR.js} +9 -9
  92. package/dist/{chunk-OYEGPK3Q.js → chunk-HFIVZJJD.js} +1 -1
  93. package/dist/{chunk-RBOKZ5ED.js → chunk-HFUI6LVF.js} +1 -1
  94. package/dist/chunk-HOIEN7O4.js +31 -0
  95. package/dist/{chunk-UHE44FC4.js → chunk-HTGJOOXE.js} +12 -4
  96. package/dist/{chunk-GWSMTN55.js → chunk-IE6BIB3L.js} +53 -1
  97. package/dist/{chunk-UHVB2TVW.js → chunk-IGZQYMZA.js} +7768 -7561
  98. package/dist/{chunk-CAYQATCT.js → chunk-J6VYWZSO.js} +1 -1
  99. package/dist/{chunk-OZDELWQP.js → chunk-JKLWQUSV.js} +1 -1
  100. package/dist/{chunk-27YDEBOP.js → chunk-JOOKM2NC.js} +2 -2
  101. package/dist/{chunk-XFSZ3IXC.js → chunk-JQZ5WP7L.js} +1 -1
  102. package/dist/{chunk-XLQUCTC2.js → chunk-JZVI2TMX.js} +3 -3
  103. package/dist/{chunk-NFNYYBD6.js → chunk-K2EJQ44S.js} +1 -1
  104. package/dist/{chunk-N4CJSWTO.js → chunk-KYKQO4VN.js} +2 -2
  105. package/dist/{chunk-2XZ76TF4.js → chunk-LO5USUM4.js} +1 -1
  106. package/dist/{chunk-TEA4ZEHB.js → chunk-M3IHARIW.js} +15 -15
  107. package/dist/{chunk-N7M2SNAF.js → chunk-M5TTYUZM.js} +2 -2
  108. package/dist/{chunk-IJYIIHGK.js → chunk-MK23FXLH.js} +1 -1
  109. package/dist/{chunk-AYESPEPQ.js → chunk-MPC3OODR.js} +40 -4
  110. package/dist/{chunk-K2VFTUAA.js → chunk-MSC5KBCE.js} +1 -1
  111. package/dist/{chunk-VPX4GVGQ.js → chunk-N6PAWR5C.js} +3 -3
  112. package/dist/{chunk-26RTKW2U.js → chunk-NJPLH762.js} +2 -2
  113. package/dist/{chunk-DQHFS4AE.js → chunk-NLVIE7VN.js} +4 -4
  114. package/dist/{chunk-3WG7IC5Z.js → chunk-O2BLY7PO.js} +1 -1
  115. package/dist/{chunk-SEC76O65.js → chunk-O2INZCGB.js} +1 -1
  116. package/dist/{chunk-2PASB3PC.js → chunk-O4K22EFS.js} +5 -5
  117. package/dist/{chunk-L27Z3PZT.js → chunk-O5U3Y5DX.js} +1 -1
  118. package/dist/{chunk-KD33HZPP.js → chunk-OD7XWF5T.js} +2 -2
  119. package/dist/{chunk-7QFFS657.js → chunk-OEGWTN6N.js} +1 -1
  120. package/dist/{chunk-Q42L7V5T.js → chunk-OL7RHRNJ.js} +1 -1
  121. package/dist/{chunk-AU4ZBCR3.js → chunk-OMZSPAK5.js} +1 -1
  122. package/dist/{chunk-3ANC4SO2.js → chunk-OPSGEOCO.js} +27 -19
  123. package/dist/{chunk-YU5LSWA2.js → chunk-PGITR2WX.js} +7 -4
  124. package/dist/{chunk-RIAH7WEL.js → chunk-PS7WBIPK.js} +10 -10
  125. package/dist/{chunk-TN3WGE3L.js → chunk-PYTF6VHF.js} +6 -4
  126. package/dist/{chunk-OIO7YMBP.js → chunk-QGQCWG7F.js} +1 -1
  127. package/dist/{chunk-TFVIXR6V.js → chunk-ROESFEBP.js} +79 -70
  128. package/dist/{chunk-YY7ZJHL3.js → chunk-RV3HR3BZ.js} +5 -5
  129. package/dist/{chunk-KWTTELUY.js → chunk-SALNTRJA.js} +47 -3
  130. package/dist/{chunk-LKWWY6WN.js → chunk-SE4NOUB6.js} +1 -1
  131. package/dist/{chunk-BOEEHWDX.js → chunk-SM5PNCDI.js} +1 -1
  132. package/dist/{chunk-ZLG2E7GC.js → chunk-SNKBI4YB.js} +2 -2
  133. package/dist/{chunk-EXEX7TSU.js → chunk-SV72WLBE.js} +13 -14
  134. package/dist/{chunk-PXLGDX2S.js → chunk-SYKUNH25.js} +39 -24
  135. package/dist/{chunk-MDOMSEK2.js → chunk-TAXMLPTE.js} +2 -2
  136. package/dist/{chunk-5BWIBP2F.js → chunk-TLDIP7Y3.js} +16 -12
  137. package/dist/{chunk-HLDUHLYO.js → chunk-TLGQQ324.js} +4 -4
  138. package/dist/{chunk-5LSMAWK5.js → chunk-U5MILT4G.js} +1 -1
  139. package/dist/{chunk-UV3I2TND.js → chunk-UDLWVQ74.js} +33 -40
  140. package/dist/{chunk-AHXRYOTC.js → chunk-UGKUGYHD.js} +1 -1
  141. package/dist/{chunk-EUP7ODOV.js → chunk-UJTLTFB6.js} +1 -1
  142. package/dist/{chunk-J424KJXV.js → chunk-V3O4AFO3.js} +9 -9
  143. package/dist/{chunk-FMYXLRJN.js → chunk-VBEDZGBW.js} +3 -3
  144. package/dist/{chunk-NRGNEP3R.js → chunk-VI2LLFW6.js} +2 -2
  145. package/dist/{chunk-PCNNMAUX.js → chunk-VLFBOKZX.js} +1645 -1461
  146. package/dist/{chunk-YSN6HPD3.js → chunk-VSM7OIG2.js} +2 -2
  147. package/dist/{chunk-4RPIEGL3.js → chunk-VXE46PXX.js} +1 -1
  148. package/dist/{chunk-B5HSHXE2.js → chunk-W2OXNTHG.js} +12 -7
  149. package/dist/{chunk-ND5SQJAB.js → chunk-WEU6WLVT.js} +2 -2
  150. package/dist/{chunk-E7GHBT2M.js → chunk-WGHJUGNU.js} +11 -9
  151. package/dist/{chunk-OOWZ6M75.js → chunk-WJIWXHXK.js} +8 -4
  152. package/dist/{chunk-NISP57R3.js → chunk-WLNHZ2OM.js} +56 -33
  153. package/dist/{chunk-X4KIL5BW.js → chunk-WQZQMADW.js} +14 -14
  154. package/dist/{chunk-DY7PQLIE.js → chunk-WTJZ5QFR.js} +42 -5
  155. package/dist/{chunk-O7TIBLSJ.js → chunk-X3IVUSOX.js} +80 -15
  156. package/dist/{chunk-2LQJHVI7.js → chunk-X3UXEB2U.js} +2 -2
  157. package/dist/{chunk-NFLH3TQ5.js → chunk-XMT4MG6W.js} +13 -10
  158. package/dist/{chunk-KHEOHL5O.js → chunk-XYP4T6TQ.js} +1 -1
  159. package/dist/{chunk-4S53OP2C.js → chunk-Y6CZFX5X.js} +65 -20
  160. package/dist/{chunk-QX4TZ2RK.js → chunk-Z642P33A.js} +72 -54
  161. package/dist/{chunk-6EG3W5AD.js → chunk-ZAWQJOTW.js} +8 -8
  162. package/dist/{chunk-FLQT2FVH.js → chunk-ZCLC3KVY.js} +1 -1
  163. package/dist/{chunk-CRRVULYR.js → chunk-ZFOV3R2L.js} +15 -3
  164. package/dist/{chunk-JAAIW4JR.js → chunk-ZO5NHAF3.js} +1 -1
  165. package/dist/{chunk-4ZQG3Z3J.js → chunk-ZYNNZ5DE.js} +2 -2
  166. package/dist/{clean-SXRW77YG.js → clean-6ODSABBF.js} +35 -33
  167. package/dist/cli.js +70 -70
  168. package/dist/{cloud-PUCWVAS2.js → cloud-IMYQB5RC.js} +4 -4
  169. package/dist/{cloud-LU4FVT33.js → cloud-NTKLXMBS.js} +9 -8
  170. package/dist/{cloudrun-SXXONVD6.js → cloudrun-JNLDP33J.js} +16 -13
  171. package/dist/{compare-K65FNAEA.js → compare-VLYZ6ZS4.js} +55 -53
  172. package/dist/{compiler-QISQISFV.js → compiler-7M2UCEWG.js} +7 -6
  173. package/dist/{component-YYCDOLP2.js → component-KMUHKZ4R.js} +4 -3
  174. package/dist/{compositions-LCQTIYIU.js → compositions-ESLWNOMS.js} +30 -29
  175. package/dist/{contactSheet-CCHQAZLA.js → contactSheet-4YF7U6U7.js} +5 -4
  176. package/dist/contract/path-policy.json +12 -2
  177. package/dist/{curve-T7JAY3EM.js → curve-7RPSNRPE.js} +22 -20
  178. package/dist/{cuts-E54SOAWH.js → cuts-KBAAZSPS.js} +23 -21
  179. package/dist/{delete-GLQNSOWH.js → delete-EP5Z7HKF.js} +14 -13
  180. package/dist/{deploy-SPMSEG67.js → deploy-MVR63JLD.js} +14 -11
  181. package/dist/{describeProject-YPTJWL3O.js → describeProject-NBVZT5EN.js} +16 -15
  182. package/dist/{destroy-FMAAH4KQ.js → destroy-DQKIT574.js} +13 -10
  183. package/dist/{deterministicFonts-OXGNMVJE.js → deterministicFonts-LYBMXXBW.js} +5 -4
  184. package/dist/{diff-OT5SHVFD.js → diff-RI3FTMOZ.js} +73 -67
  185. package/dist/{dist-T62DJJZX.js → dist-G7VFX23I.js} +8 -4
  186. package/dist/{dist-RYTNYHMF.js → dist-LRGTXDSM.js} +3 -3
  187. package/dist/{dist-EO7BILWH.js → dist-TOOMD57O.js} +21 -17
  188. package/dist/{doctor-L4SNKUBM.js → doctor-43YNRCRB.js} +25 -24
  189. package/dist/{energy-AXQGYZF6.js → energy-YCH36KCC.js} +23 -21
  190. package/dist/{events-7QP5H6PW.js → events-6RJBITYN.js} +28 -25
  191. package/dist/{events-5T25R4EH.js → events-JCPYG3CD.js} +6 -6
  192. package/dist/{events-EBA6KHJV.js → events-VUR27EF6.js} +12 -11
  193. package/dist/{execute-PTHC7Y5Q.js → execute-OXMKWIFI.js} +45 -44
  194. package/dist/{extract-76UPXPJC.js → extract-XGD2RDEX.js} +25 -23
  195. package/dist/{face-YZON2N2E.js → face-XCNWNTGN.js} +24 -22
  196. package/dist/{feedback-KAYKPPHI.js → feedback-JNFDVBFV.js} +27 -26
  197. package/dist/{ffmpeg-T3KK5XKT.js → ffmpeg-YQLAJUEA.js} +15 -14
  198. package/dist/{figma-NJ6CAJGV.js → figma-XXGHYEB3.js} +3 -3
  199. package/dist/fontLocalizeCli.js +23 -21
  200. package/dist/{frames-KNR4CSB4.js → frames-PEMWFRRY.js} +25 -23
  201. package/dist/{generate-ISCPAKHT.js → generate-H5M4QSJR.js} +42 -40
  202. package/dist/{get-X7QNC3PE.js → get-R6Y2OE5P.js} +14 -13
  203. package/dist/{gpuPolicy-ZXN5S3HE.js → gpuPolicy-2WVDQYZA.js} +15 -14
  204. package/dist/{grade-compare-XD3IONCL.js → grade-compare-KFXPZFDL.js} +58 -54
  205. package/dist/{gsapParserAcorn-SKGP4R4N.js → gsapParserAcorn-RODCGO2L.js} +1 -1
  206. package/dist/hangReport.js +2 -2
  207. package/dist/{heifImagePrep-EFBHDH4Z.js → heifImagePrep-VLKYA5QZ.js} +19 -17
  208. package/dist/{help-VUFIY5X4.js → help-T3XUX5RI.js} +2 -2
  209. package/dist/{history-OM3MHRB2.js → history-QJPUCUUC.js} +26 -21
  210. package/dist/hyperframe.manifest.json +1 -1
  211. package/dist/hyperframe.runtime.iife.js +76 -76
  212. package/dist/hyperframes-player.global.js +1 -1
  213. package/dist/{index-gen-OPMQ5WSN.js → index-gen-3DWPA4FO.js} +14 -12
  214. package/dist/{info-G64344ST.js → info-556DHJHJ.js} +26 -26
  215. package/dist/{init-2N6SDLZB.js → init-P62TPWR3.js} +61 -56
  216. package/dist/{ink-T5BJE4D2.js → ink-SRN65OZH.js} +23 -21
  217. package/dist/{inspect-6I4YSARX.js → inspect-U5FWQQFB.js} +54 -53
  218. package/dist/{installer-JNQKFCTN.js → installer-3TNMANQV.js} +9 -8
  219. package/dist/{keyframes-PT3H7WHD.js → keyframes-FPGEFGCH.js} +63 -28
  220. package/dist/{lambda-NEQXIHUM.js → lambda-YJY2MYWL.js} +25 -24
  221. package/dist/{layout-FRWUKOGX.js → layout-QIKSVA44.js} +54 -53
  222. package/dist/{lint-GXPONOPU.js → lint-RD33ESM5.js} +20 -20
  223. package/dist/{lintProject-J4YTLKPW.js → lintProject-ZWLXB3A2.js} +3 -3
  224. package/dist/{list-JO7WSM6Y.js → list-FFO3WOB2.js} +14 -13
  225. package/dist/{localPage-XDWFSE4K.js → localPage-DHIBMNJH.js} +16 -15
  226. package/dist/{login-XMFEIEXG.js → login-IMFRQOEQ.js} +8 -8
  227. package/dist/{logout-CCATTNTL.js → logout-SLBKP67J.js} +4 -4
  228. package/dist/{look-U77ADJ4V.js → look-ZZHJYSPC.js} +23 -21
  229. package/dist/{manager-ZRETV4LQ.js → manager-U4WEPCLV.js} +5 -5
  230. package/dist/{manager-RNMX2WTR.js → manager-V4LGD4HB.js} +16 -15
  231. package/dist/{manifest-QSJYVERU.js → manifest-TSKRUXZ5.js} +5 -1
  232. package/dist/{measure-JNJAPVVN.js → measure-ZRBVN45B.js} +11 -11
  233. package/dist/{media-treatment-MFNKKPM7.js → media-treatment-3I2CMQJZ.js} +30 -25
  234. package/dist/{media-use-ZKHL2IN2.js → media-use-2OYJ3CCN.js} +8 -8
  235. package/dist/{models-PGO2ERAU.js → models-PRW7EWSV.js} +20 -19
  236. package/dist/{motionShot-AG4LR5Q5.js → motionShot-VWILMLHQ.js} +39 -30
  237. package/dist/{normalize-audio-FO3JCPD3.js → normalize-audio-42XMF35K.js} +19 -17
  238. package/dist/{oauth-SAVP2YM4.js → oauth-V3HSFZRE.js} +2 -2
  239. package/dist/{open-ZI6KK3GM.js → open-D52MJZQA.js} +31 -28
  240. package/dist/{parakeetRunner-CBO3HRL6.js → parakeetRunner-ZR2JWQZH.js} +23 -22
  241. package/dist/{pipeline-VWVNH5ZC.js → pipeline-W3H4JA6H.js} +18 -17
  242. package/dist/{plan-UHZYW3K2.js → plan-2HQOFJO7.js} +34 -33
  243. package/dist/{play-IVTXE4JW.js → play-G5XDRDIZ.js} +49 -41
  244. package/dist/{preflight-QJNKKMPE.js → preflight-W2JDYF3T.js} +18 -17
  245. package/dist/{present-NB6DAJ6K.js → present-CYMTHQFM.js} +68 -51
  246. package/dist/{preview-FIWAZ5PX.js → preview-DTQPQZTK.js} +51 -49
  247. package/dist/{probe-VQJOUG65.js → probe-WZJK3YQI.js} +23 -21
  248. package/dist/{producer-NP6X5UBL.js → producer-2BSMSO6I.js} +1 -1
  249. package/dist/{progress-IY6U35WH.js → progress-KRDVC24C.js} +4 -1
  250. package/dist/{projectConfig-UVA26HJW.js → projectConfig-BYRVYLCC.js} +12 -11
  251. package/dist/{publication-LYPU7NTZ.js → publication-UCFJLELD.js} +7 -6
  252. package/dist/{publish-MRQ2K62E.js → publish-KXVPSWCO.js} +36 -35
  253. package/dist/{refresh-X5ZLKQO5.js → refresh-2GVNKDQE.js} +4 -4
  254. package/dist/{remove-background-RG6DCWOW.js → remove-background-O7BZNS3X.js} +19 -18
  255. package/dist/{render-XWBMMSC5.js → render-DGAP4Q2Z.js} +81 -67
  256. package/dist/{render-6B7YPN7H.js → render-QOWXGWQZ.js} +55 -54
  257. package/dist/{render-CM4MCNVA.js → render-TYS3LCIQ.js} +10 -8
  258. package/dist/{render-batch-Y3RRNDNJ.js → render-batch-TEQRGAUC.js} +10 -8
  259. package/dist/renderSetupWorker.js +8 -8
  260. package/dist/{resolver-K6VAEZVH.js → resolver-RN2JGGQL.js} +9 -8
  261. package/dist/{reverse-5RDRLKAP.js → reverse-FUARFEG2.js} +1 -1
  262. package/dist/{run-OQK3QU4I.js → run-V722HMUG.js} +12 -11
  263. package/dist/{sam-A4NXDWSU.js → sam-KHLM2DJA.js} +4 -4
  264. package/dist/{screenshotCapture-VDITRAK2.js → screenshotCapture-4BB4LUMX.js} +18 -17
  265. package/dist/{service-C3UT4LYP.js → service-ZPCHJY6B.js} +24 -23
  266. package/dist/{share-JU3IDHUV.js → share-PXUN7AH7.js} +29 -28
  267. package/dist/{sherpa-Z2Z4XLXV.js → sherpa-LT6Y7IGM.js} +22 -21
  268. package/dist/sherpaWorker.js +6 -3
  269. package/dist/{sites-QK3F4AUS.js → sites-WWCABDSX.js} +4 -1
  270. package/dist/skills/hyperframes/SKILL.md +2 -2
  271. package/dist/skills/hyperframes/references/format.md +11 -2
  272. package/dist/skills/hyperframes/references/overlays.md +1 -1
  273. package/dist/skills/hyperframes/references/plugin-installation.md +45 -22
  274. package/dist/skills/hyperframes/references/sound.md +1 -0
  275. package/dist/skills/hyperframes/scripts/plugin-cli.mjs +61 -18
  276. package/dist/skills/hyperframes-cli/SKILL.md +2 -2
  277. package/dist/skills/media-use/SKILL.md +1 -1
  278. package/dist/skills/media-use/audio/scripts/audio.mjs +24 -7
  279. package/dist/skills/media-use/audio/scripts/carve.mjs +10 -82
  280. package/dist/skills/media-use/audio/scripts/lib/audio-carve.mjs +4 -0
  281. package/dist/skills/media-use/audio/scripts/lib/bgm.mjs +4 -1
  282. package/dist/skills/media-use/audio/scripts/lib/media-record.mjs +25 -7
  283. package/dist/skills/media-use/audio/scripts/lib/project-path.mjs +56 -0
  284. package/dist/skills/media-use/audio/scripts/lib/python.mjs +9 -1
  285. package/dist/skills/media-use/audio/scripts/lib/recording.mjs +66 -3
  286. package/dist/skills/media-use/audio/scripts/wait-bgm.mjs +12 -7
  287. package/dist/skills/media-use/references/audio.md +2 -2
  288. package/dist/skills/media-use/references/mixing.md +1 -1
  289. package/dist/skills/media-use/scripts/lib/bundled-sfx-provider.mjs +27 -2
  290. package/dist/skills/media-use/scripts/lib/index-gen.mjs +13 -11
  291. package/dist/skills/media-use/scripts/lib/local-media-search.mjs +52 -23
  292. package/dist/skills/media-use/scripts/lib/ltx-video-provider.mjs +3 -1
  293. package/dist/skills/media-use/scripts/lib/manifest.mjs +51 -4
  294. package/dist/skills/media-use/scripts/resolve.mjs +4 -14
  295. package/dist/skills/media-use/scripts/transcribe.mjs +19 -3
  296. package/dist/{skills-24YEOJGP.js → skills-G63W5GD5.js} +17 -16
  297. package/dist/{skillsUpdateCheck-5R4JJ27G.js → skillsUpdateCheck-2T3JVDAA.js} +6 -6
  298. package/dist/{snapshot-T4REEKFX.js → snapshot-EVSKTVDG.js} +90 -77
  299. package/dist/{src-RMJVAEKT.js → src-K5FSMLTB.js} +23 -21
  300. package/dist/{src-EKGFNTTY.js → src-R57EQQSI.js} +29 -20
  301. package/dist/{start-E5RIH3KS.js → start-XBCYKGBV.js} +41 -39
  302. package/dist/{state-7OIPR4BG.js → state-FO64CPYE.js} +4 -1
  303. package/dist/{staticProjectServer-LEM5W3S5.js → staticProjectServer-Q6VR7CXT.js} +33 -31
  304. package/dist/{status-CSHJWWOP.js → status-E5XIWRCQ.js} +37 -34
  305. package/dist/studio/assets/{hyperframes-player-BroIQA4E.js → hyperframes-player-B78JDyI_.js} +1 -1
  306. package/dist/studio/assets/{index-Be7DZynj.js → index-D7ICtobF.js} +190 -190
  307. package/dist/studio/assets/{index-CiF0D62S.js → index-ww7-RmuM.js} +1 -1
  308. package/dist/studio/assets/{pausedVideoDecoder-RXcvblHS.js → pausedVideoDecoder-Dbe8Cmab.js} +1 -1
  309. package/dist/studio/index.html +1 -1
  310. package/dist/{studio-api-COJYCMRI.js → studio-api-GMJVYGET.js} +21 -17
  311. package/dist/{studioSelectionClient-W2S3H2VO.js → studioSelectionClient-S46TNAAZ.js} +2 -1
  312. package/dist/{studioServer-62ZTBLFM.js → studioServer-MIQCMK6U.js} +130 -102
  313. package/dist/subCompositionWorker.js +1162 -0
  314. package/dist/{sync-CLRYHWYE.js → sync-WJOFN6VN.js} +23 -21
  315. package/dist/{synthesize-Z2H32QPU.js → synthesize-FXM7ZD6J.js} +6 -5
  316. package/dist/{system-2YOII5LZ.js → system-DBUN5UDD.js} +3 -3
  317. package/dist/{telemetry-DWA36DFX.js → telemetry-HZ4P4DMC.js} +12 -11
  318. package/dist/{templates-LXMQR35F.js → templates-KFZZSSKW.js} +139 -46
  319. package/dist/{timeline-LMKTDKRT.js → timeline-5M6DPCXF.js} +38 -36
  320. package/dist/{tokens-VJ765KFG.js → tokens-H4NPNRFR.js} +3 -2
  321. package/dist/{transcribe-TICRK4IY.js → transcribe-6STI2ALX.js} +48 -46
  322. package/dist/{transcribe-3WASFP7Z.js → transcribe-7PE5UH7J.js} +19 -18
  323. package/dist/{tts-5YJV6UXX.js → tts-D7CLD3AD.js} +1 -1
  324. package/dist/{update-Q26QGCBW.js → update-H3T3AVVG.js} +19 -18
  325. package/dist/{updateCheck-7R4S46TT.js → updateCheck-TLCXUNBV.js} +5 -5
  326. package/dist/{upgrade-76TFHAGI.js → upgrade-BZVTMCQU.js} +9 -8
  327. package/dist/{urlDownloader-AE4UQI5A.js → urlDownloader-FJXNC3IM.js} +14 -13
  328. package/dist/{validate-BEYREWEL.js → validate-WTRVCEL5.js} +40 -38
  329. package/dist/{video-47AVLNWM.js → video-TVO2U5F2.js} +18 -17
  330. package/dist/{voices-5O6OAL6H.js → voices-F3EW43LX.js} +40 -38
  331. package/dist/warmCheck.js +66 -63
  332. package/dist/warmCheckClient.js +2 -2
  333. package/package.json +2 -1
  334. package/dist/chunk-XGEJPKRY.js +0 -5069
  335. package/dist/skills/hyperframes/scripts/lib/main-module.test.mjs +0 -46
  336. package/dist/skills/hyperframes/scripts/lib/windows-exe-search.test.mjs +0 -149
  337. package/dist/skills/hyperframes/scripts/plugin-cli.test.mjs +0 -207
  338. package/dist/skills/media-use/audio/scripts/audio.test.mjs +0 -166
  339. package/dist/skills/media-use/audio/scripts/carve.test.mjs +0 -254
  340. package/dist/skills/media-use/audio/scripts/gemini-pipeline.test.mjs +0 -131
  341. package/dist/skills/media-use/audio/scripts/heygen-tts.test.mjs +0 -38
  342. package/dist/skills/media-use/audio/scripts/heygen-voice.test.mjs +0 -233
  343. package/dist/skills/media-use/audio/scripts/lib/audio-meta.test.mjs +0 -136
  344. package/dist/skills/media-use/audio/scripts/lib/bgm.test.mjs +0 -74
  345. package/dist/skills/media-use/audio/scripts/lib/concurrency.test.mjs +0 -41
  346. package/dist/skills/media-use/audio/scripts/lib/gemini-auth.test.mjs +0 -86
  347. package/dist/skills/media-use/audio/scripts/lib/gemini-tts.test.mjs +0 -253
  348. package/dist/skills/media-use/audio/scripts/lib/heygen.test.mjs +0 -627
  349. package/dist/skills/media-use/audio/scripts/lib/media-record.test.mjs +0 -239
  350. package/dist/skills/media-use/audio/scripts/lib/python.test.mjs +0 -182
  351. package/dist/skills/media-use/audio/scripts/lib/sfx.test.mjs +0 -331
  352. package/dist/skills/media-use/audio/scripts/lib/tts.cleanup.test.mjs +0 -181
  353. package/dist/skills/media-use/audio/scripts/lib/tts.spawn.test.mjs +0 -183
  354. package/dist/skills/media-use/audio/scripts/lib/tts.test.mjs +0 -280
  355. package/dist/skills/media-use/audio/scripts/lib/voice-credit.test.mjs +0 -21
  356. package/dist/skills/media-use/audio/scripts/recording.test.mjs +0 -139
  357. package/dist/skills/media-use/audio/scripts/trusted-program.test.mjs +0 -106
  358. package/dist/skills/media-use/audio/scripts/wait-bgm.test.mjs +0 -108
  359. package/dist/skills/media-use/scripts/compatibility.test.mjs +0 -41
  360. package/dist/skills/media-use/scripts/dither.test.mjs +0 -176
  361. package/dist/skills/media-use/scripts/lib/adopt.test.mjs +0 -143
  362. package/dist/skills/media-use/scripts/lib/bundled-sfx-provider.test.mjs +0 -139
  363. package/dist/skills/media-use/scripts/lib/cache.test.mjs +0 -110
  364. package/dist/skills/media-use/scripts/lib/candidates.test.mjs +0 -155
  365. package/dist/skills/media-use/scripts/lib/codex-provider.test.mjs +0 -34
  366. package/dist/skills/media-use/scripts/lib/config-lock.test.mjs +0 -79
  367. package/dist/skills/media-use/scripts/lib/coverage.test.mjs +0 -136
  368. package/dist/skills/media-use/scripts/lib/credit-limit.test.mjs +0 -39
  369. package/dist/skills/media-use/scripts/lib/cube-build.test.mjs +0 -80
  370. package/dist/skills/media-use/scripts/lib/cube-validate.test.mjs +0 -130
  371. package/dist/skills/media-use/scripts/lib/cutlist.test.mjs +0 -174
  372. package/dist/skills/media-use/scripts/lib/duck.test.mjs +0 -319
  373. package/dist/skills/media-use/scripts/lib/error-diffusion.test.mjs +0 -102
  374. package/dist/skills/media-use/scripts/lib/freeze.test.mjs +0 -138
  375. package/dist/skills/media-use/scripts/lib/grade-analyzer.test.mjs +0 -285
  376. package/dist/skills/media-use/scripts/lib/heygen-cli.test.mjs +0 -315
  377. package/dist/skills/media-use/scripts/lib/heygen-search.test.mjs +0 -49
  378. package/dist/skills/media-use/scripts/lib/heygen-video-provider.test.mjs +0 -435
  379. package/dist/skills/media-use/scripts/lib/local-media-search.test.mjs +0 -23
  380. package/dist/skills/media-use/scripts/lib/local-models.test.mjs +0 -220
  381. package/dist/skills/media-use/scripts/lib/local-run.test.mjs +0 -121
  382. package/dist/skills/media-use/scripts/lib/logo-provider.test.mjs +0 -312
  383. package/dist/skills/media-use/scripts/lib/ltx-video-provider.test.mjs +0 -316
  384. package/dist/skills/media-use/scripts/lib/lut-preset-provider.test.mjs +0 -199
  385. package/dist/skills/media-use/scripts/lib/manifest.test.mjs +0 -397
  386. package/dist/skills/media-use/scripts/lib/media-fetch.test.mjs +0 -197
  387. package/dist/skills/media-use/scripts/lib/media-home.test.mjs +0 -61
  388. package/dist/skills/media-use/scripts/lib/mflux-provider.test.mjs +0 -174
  389. package/dist/skills/media-use/scripts/lib/misses.test.mjs +0 -89
  390. package/dist/skills/media-use/scripts/lib/npx-sync.test.mjs +0 -41
  391. package/dist/skills/media-use/scripts/lib/openverse.test.mjs +0 -219
  392. package/dist/skills/media-use/scripts/lib/parakeet-words.test.mjs +0 -44
  393. package/dist/skills/media-use/scripts/lib/prefs-store.concurrent.test.mjs +0 -173
  394. package/dist/skills/media-use/scripts/lib/prefs-store.test.mjs +0 -245
  395. package/dist/skills/media-use/scripts/lib/probe.test.mjs +0 -221
  396. package/dist/skills/media-use/scripts/lib/recipe-store.test.mjs +0 -391
  397. package/dist/skills/media-use/scripts/lib/registry.test.mjs +0 -261
  398. package/dist/skills/media-use/scripts/lib/search.test.mjs +0 -32
  399. package/dist/skills/media-use/scripts/lib/specs.test.mjs +0 -157
  400. package/dist/skills/media-use/scripts/lib/stats.test.mjs +0 -165
  401. package/dist/skills/media-use/scripts/lib/telemetry.test.mjs +0 -550
  402. package/dist/skills/media-use/scripts/lib/test-home.test.mjs +0 -10
  403. package/dist/skills/media-use/scripts/lib/transcriptCutFade.test.mjs +0 -33
  404. package/dist/skills/media-use/scripts/lib/tts-local-provider.test.mjs +0 -59
  405. package/dist/skills/media-use/scripts/lib/usage.test.mjs +0 -54
  406. package/dist/skills/media-use/scripts/lib/voice-provider.test.mjs +0 -46
  407. package/dist/skills/media-use/scripts/resolve-plugin.test.mjs +0 -86
  408. package/dist/skills/media-use/scripts/transcribe.test.mjs +0 -155
  409. package/dist/skills/media-use/scripts/transcript-cut.test.mjs +0 -341
  410. package/dist/{chunk-BAWGEGKD.js → chunk-XMAU5ZQX.js} +3 -3
@@ -4,6 +4,10 @@ import { dirname as __hf_dirname } from "node:path";
4
4
  var require = __hf_createRequire(import.meta.url);
5
5
  var __filename = __hf_fileURLToPath(import.meta.url);
6
6
  var __dirname = __hf_dirname(__filename);
7
+ import {
8
+ removeTreeBestEffort,
9
+ removeTreeBestEffortAsync
10
+ } from "./chunk-Z5J67X44.js";
7
11
  import {
8
12
  NonPublicHostError,
9
13
  assertPublicHostname,
@@ -14,10 +18,6 @@ import {
14
18
  resolvePublicAddress,
15
19
  startCaptureProxy
16
20
  } from "./chunk-OSKSTJNQ.js";
17
- import {
18
- removeTreeBestEffort,
19
- removeTreeBestEffortAsync
20
- } from "./chunk-Z5J67X44.js";
21
21
  import {
22
22
  PREVIEW_FOR_ANOTHER_SITE_META
23
23
  } from "./chunk-YXX6CIHL.js";
@@ -36,7 +36,7 @@ import {
36
36
  removeScratch,
37
37
  renameWithRetry,
38
38
  renameWithRetryAsync
39
- } from "./chunk-KCF6Q54R.js";
39
+ } from "./chunk-DL6PEJWH.js";
40
40
  import {
41
41
  DISTRIBUTED_FPS,
42
42
  HF_COLOR_GROUP_ATTR,
@@ -66,12 +66,11 @@ import {
66
66
  resolveAuthoredTimingWindow,
67
67
  toFps,
68
68
  validateVariables
69
- } from "./chunk-4IUOWNDS.js";
69
+ } from "./chunk-5IUVWP3A.js";
70
70
  import {
71
71
  AUDIO_GROUP_RENDER_ID_ATTR,
72
72
  AUTHORED_SOURCE_BEGIN,
73
73
  AUTHORED_SOURCE_END,
74
- COLOR_GRADING_SOURCE_HIDDEN_ATTR,
75
74
  COMPOSITION_SOURCE_URL,
76
75
  HF_AUDIO_AUTOMATION_ATTR,
77
76
  HF_AUDIO_FX_ATTR,
@@ -111,12 +110,15 @@ import {
111
110
  sourceTimeAt,
112
111
  timeAtSourceTime,
113
112
  volumeSegmentSampleCount
114
- } from "./chunk-XGEJPKRY.js";
113
+ } from "./chunk-2RUCE54M.js";
115
114
  import {
116
115
  isPrivateFileUnder,
117
116
  isSafePath,
118
117
  isStudioPrivatePath
119
- } from "./chunk-KWTTELUY.js";
118
+ } from "./chunk-SALNTRJA.js";
119
+ import {
120
+ terminalText
121
+ } from "./chunk-MK23FXLH.js";
120
122
  import {
121
123
  browserPathFromEnv,
122
124
  buildChromeLaunchEnv,
@@ -124,11 +126,12 @@ import {
124
126
  compareBrowserVersionsDescending,
125
127
  exceedsChromeCeiling,
126
128
  isManagedChromeDir,
129
+ isPinnedHeadlessShell,
127
130
  pickSharedShell
128
- } from "./chunk-LEIR7IDJ.js";
131
+ } from "./chunk-6LU6JICP.js";
129
132
  import {
130
133
  resolveReferencedStart
131
- } from "./chunk-UV3I2TND.js";
134
+ } from "./chunk-UDLWVQ74.js";
132
135
  import {
133
136
  isWithinProjectRoot,
134
137
  resolveProjectRelativeSrc
@@ -141,13 +144,13 @@ import {
141
144
  hostCpuCount,
142
145
  isLowMemorySystem,
143
146
  usableCpuCount
144
- } from "./chunk-L27Z3PZT.js";
147
+ } from "./chunk-O5U3Y5DX.js";
145
148
  import {
146
149
  isPathInside
147
150
  } from "./chunk-IH2C53YV.js";
148
151
  import {
149
152
  readCompositionVariables
150
- } from "./chunk-VCKUDUPN.js";
153
+ } from "./chunk-7IMHPBSH.js";
151
154
  import {
152
155
  parseHTML
153
156
  } from "./chunk-GWTIFRF5.js";
@@ -167,9 +170,11 @@ import {
167
170
  import {
168
171
  FFMPEG_PATH_ENV,
169
172
  FFPROBE_PATH_ENV,
173
+ SELF_CONTAINED_FORMATS,
170
174
  findFfBinary,
171
- findTrustedExecutable
172
- } from "./chunk-GWSMTN55.js";
175
+ findTrustedExecutable,
176
+ mediaInputFormatArgs
177
+ } from "./chunk-IE6BIB3L.js";
173
178
 
174
179
  // ../engine/src/services/referenceBackground.ts
175
180
  var REFERENCE_BACKGROUND_FIELD = "reference_background";
@@ -1034,7 +1039,7 @@ function scanHtmlOpeningTags(html) {
1034
1039
 
1035
1040
  // ../engine/src/services/browserManager.ts
1036
1041
  import { execFileSync } from "child_process";
1037
- import { existsSync as existsSync2, readdirSync, statSync } from "fs";
1042
+ import { existsSync as existsSync2, readdirSync } from "fs";
1038
1043
  import { join as join3 } from "path";
1039
1044
  import { homedir } from "os";
1040
1045
 
@@ -1348,16 +1353,9 @@ function isSoftwareWebGlRenderer(rendererInfo) {
1348
1353
  const renderer = rendererInfo.trim().toLowerCase();
1349
1354
  return SOFTWARE_WEBGL_RENDERER_TOKENS.some((token) => renderer.includes(token));
1350
1355
  }
1351
- async function getPuppeteer() {
1356
+ async function getPuppeteerCore() {
1352
1357
  if (_puppeteer) return _puppeteer;
1353
- try {
1354
- const mod = await import("puppeteer");
1355
- _puppeteer = mod.default;
1356
- } catch {
1357
- const mod = await import("puppeteer-core");
1358
- _puppeteer = mod.default;
1359
- }
1360
- if (!_puppeteer) throw new Error("Neither puppeteer nor puppeteer-core found");
1358
+ _puppeteer = (await import("puppeteer-core")).default;
1361
1359
  return _puppeteer;
1362
1360
  }
1363
1361
  var GPU_PROBE_TIMEOUT_MS = 15e3;
@@ -1423,14 +1421,6 @@ var CACHED_HEADLESS_SHELL_EXECUTABLES = {
1423
1421
  function cachedHeadlessShellExecutable(hostPlatform = process.platform, hostArch = process.arch) {
1424
1422
  return CACHED_HEADLESS_SHELL_EXECUTABLES[`${hostPlatform}/${hostArch}`];
1425
1423
  }
1426
- function isNonEmptyFile(path) {
1427
- try {
1428
- const stat = statSync(path, { throwIfNoEntry: false });
1429
- return stat?.isFile() === true && stat.size > 0;
1430
- } catch {
1431
- return false;
1432
- }
1433
- }
1434
1424
  function findCachedHeadlessShell(baseDir) {
1435
1425
  if (!existsSync2(baseDir)) return void 0;
1436
1426
  const executable = cachedHeadlessShellExecutable();
@@ -1441,7 +1431,7 @@ function findCachedHeadlessShell(baseDir) {
1441
1431
  for (const version of versions) {
1442
1432
  if (exceedsChromeCeiling(version, ceiling)) continue;
1443
1433
  const binary = join3(baseDir, version, ...executable);
1444
- if (isNonEmptyFile(binary)) return binary;
1434
+ if (isPinnedHeadlessShell(binary)) return binary;
1445
1435
  }
1446
1436
  } catch {
1447
1437
  }
@@ -1453,7 +1443,7 @@ function findSharedHeadlessShell(baseDir) {
1453
1443
  try {
1454
1444
  return pickSharedShell(readdirSync(baseDir), (version) => {
1455
1445
  const binary = join3(baseDir, version, ...executable);
1456
- return isNonEmptyFile(binary) ? binary : void 0;
1446
+ return isPinnedHeadlessShell(binary) ? binary : void 0;
1457
1447
  });
1458
1448
  } catch {
1459
1449
  return void 0;
@@ -1465,7 +1455,7 @@ function findManagedHeadlessShell(baseDir) {
1465
1455
  try {
1466
1456
  const version = readdirSync(baseDir).find(isManagedChromeDir);
1467
1457
  const binary = version && join3(baseDir, version, ...executable);
1468
- return binary && isNonEmptyFile(binary) ? binary : void 0;
1458
+ return binary && isPinnedHeadlessShell(binary) ? binary : void 0;
1469
1459
  } catch {
1470
1460
  return void 0;
1471
1461
  }
@@ -1487,42 +1477,16 @@ function resolveHeadlessShellPath(config) {
1487
1477
  const shared = join3(homedir(), ".cache", "puppeteer", "chrome-headless-shell");
1488
1478
  return findManagedHeadlessShell(ours) ?? findSharedHeadlessShell(shared) ?? findCachedHeadlessShell(ours);
1489
1479
  }
1480
+ function launchableBrowserPath(config) {
1481
+ const path = resolveHeadlessShellPath(config);
1482
+ if (path) return path;
1483
+ throw new Error(
1484
+ "[BrowserManager] No verified browser to render with. Run `npx hyperframes browser ensure`, or name one in PRODUCER_HEADLESS_SHELL_PATH."
1485
+ );
1486
+ }
1490
1487
  function resolveFullChromePath() {
1491
- const baseDir = join3(homedir(), ".cache", "puppeteer", "chrome");
1492
- let versions;
1493
- try {
1494
- versions = readdirSync(baseDir).sort(compareBrowserVersionsDescending);
1495
- } catch {
1496
- return void 0;
1497
- }
1498
- for (const version of versions) {
1499
- const candidates = [
1500
- join3(
1501
- baseDir,
1502
- version,
1503
- "chrome-mac-arm64",
1504
- "Google Chrome for Testing.app",
1505
- "Contents",
1506
- "MacOS",
1507
- "Google Chrome for Testing"
1508
- ),
1509
- join3(
1510
- baseDir,
1511
- version,
1512
- "chrome-mac-x64",
1513
- "Google Chrome for Testing.app",
1514
- "Contents",
1515
- "MacOS",
1516
- "Google Chrome for Testing"
1517
- ),
1518
- join3(baseDir, version, "chrome-linux64", "chrome"),
1519
- join3(baseDir, version, "chrome-win64", "chrome.exe")
1520
- ];
1521
- for (const binary of candidates) {
1522
- if (existsSync2(binary)) return binary;
1523
- }
1524
- }
1525
- return void 0;
1488
+ const named = browserPathFromEnv();
1489
+ return named && existsSync2(named.path) ? named.path : void 0;
1526
1490
  }
1527
1491
  var ENABLE_BROWSER_POOL = DEFAULT_CONFIG.enableBrowserPool;
1528
1492
  var BEGINFRAME_ONLY_FLAGS = /* @__PURE__ */ new Set([
@@ -1683,7 +1647,7 @@ async function probeBeginFrameSupport(browser, timeoutMs = BEGINFRAME_PROBE_TIME
1683
1647
  var _autoBrowserGpuModeCache;
1684
1648
  async function getPuppeteerOrNull() {
1685
1649
  try {
1686
- return await getPuppeteer();
1650
+ return await getPuppeteerCore();
1687
1651
  } catch {
1688
1652
  return null;
1689
1653
  }
@@ -1730,7 +1694,7 @@ async function probeWebGlMode(ppt, options, env, label = "") {
1730
1694
  const info = await probeHardwareWebGlInfo(ppt, {
1731
1695
  args: getHardwareGpuProbeArgs(options.platform ?? process.platform),
1732
1696
  browserTimeout: options.browserTimeout ?? DEFAULT_CONFIG.browserTimeout,
1733
- executablePath: options.chromePath ?? resolveHeadlessShellPath({}),
1697
+ executablePath: launchableBrowserPath({ chromePath: options.chromePath }),
1734
1698
  probeLifecycle: options.probeLifecycle,
1735
1699
  env
1736
1700
  });
@@ -1827,7 +1791,7 @@ function createBrowserLaunchFingerprint(chromeArgs, config) {
1827
1791
  forceScreenshot: DEFAULT_CONFIG.forceScreenshot,
1828
1792
  ...config
1829
1793
  };
1830
- const headlessShell = resolveHeadlessShellPath(launchConfig);
1794
+ const headlessShell = launchableBrowserPath(launchConfig);
1831
1795
  const beginFrameControlEnabled = chromeArgs.includes("--enable-begin-frame-control");
1832
1796
  const requestedCaptureMode = headlessShell && process.platform === "linux" && !launchConfig.forceScreenshot && beginFrameControlEnabled ? "beginframe" : "screenshot";
1833
1797
  return {
@@ -1875,7 +1839,7 @@ async function publicOnlyNetwork(pageServerHost) {
1875
1839
  }
1876
1840
  }
1877
1841
  async function launchBrowser(fingerprint) {
1878
- const ppt = await getPuppeteer();
1842
+ const ppt = await getPuppeteerCore();
1879
1843
  const env = launchEnv(fingerprint);
1880
1844
  let captureMode = fingerprint.requestedCaptureMode;
1881
1845
  let browser;
@@ -3045,6 +3009,8 @@ function chunkCrc32(chunkType, chunkData) {
3045
3009
  }
3046
3010
 
3047
3011
  // ../engine/src/utils/alphaBlit.ts
3012
+ var MAX_RGB48LE_PIXELS = 8192 * 8192;
3013
+ var MAX_SCREENSHOT_PIXELS = 16384 * 16384;
3048
3014
  function paeth(a, b, c) {
3049
3015
  const p = a + b - c;
3050
3016
  const pa = Math.abs(p - a);
@@ -3054,7 +3020,37 @@ function paeth(a, b, c) {
3054
3020
  if (pb <= pc) return b;
3055
3021
  return c;
3056
3022
  }
3057
- function decodePngRaw(buf, caller) {
3023
+ function inflateScanlines(idatChunks, header, caller, maxPixels) {
3024
+ const { width, height, bitDepth, colorType } = header;
3025
+ if (bitDepth !== 8 && bitDepth !== 16) {
3026
+ throw new Error(`${caller}: unsupported bit depth ${bitDepth} (expected 8 or 16)`);
3027
+ }
3028
+ if (width === 0 || height === 0 || width * height > maxPixels) {
3029
+ throw new Error(
3030
+ `${caller}: ${width}x${height} PNG is outside the supported size (max ${maxPixels} pixels)`
3031
+ );
3032
+ }
3033
+ const channels = colorType === 6 ? 4 : 3;
3034
+ const bpp = channels * (bitDepth / 8);
3035
+ const stride = width * bpp;
3036
+ const expectedLength = height * (stride + 1);
3037
+ let decompressed;
3038
+ try {
3039
+ decompressed = inflateSync(Buffer.concat(idatChunks), { maxOutputLength: expectedLength });
3040
+ } catch (err) {
3041
+ throw new Error(
3042
+ `${caller}: image data does not inflate to ${expectedLength} bytes for ${width}x${height}`,
3043
+ { cause: err }
3044
+ );
3045
+ }
3046
+ if (decompressed.length !== expectedLength) {
3047
+ throw new Error(
3048
+ `${caller}: image data inflates to ${decompressed.length} bytes, expected ${expectedLength}`
3049
+ );
3050
+ }
3051
+ return { decompressed, bpp, stride };
3052
+ }
3053
+ function decodePngRaw(buf, caller, maxPixels) {
3058
3054
  if (buf[0] !== 137 || buf[1] !== 80 || buf[2] !== 78 || buf[3] !== 71 || buf[4] !== 13 || buf[5] !== 10 || buf[6] !== 26 || buf[7] !== 10) {
3059
3055
  throw new Error(`${caller}: not a PNG file`);
3060
3056
  }
@@ -3095,11 +3091,12 @@ function decodePngRaw(buf, caller) {
3095
3091
  `${caller}: Adam7-interlaced PNGs are not supported (interlace method ${interlace})`
3096
3092
  );
3097
3093
  }
3098
- const channels = colorType === 6 ? 4 : 3;
3099
- const bpp = channels * (bitDepth / 8);
3100
- const stride = width * bpp;
3101
- const compressed = Buffer.concat(idatChunks);
3102
- const decompressed = inflateSync(compressed);
3094
+ const { decompressed, bpp, stride } = inflateScanlines(
3095
+ idatChunks,
3096
+ { width, height, bitDepth, colorType },
3097
+ caller,
3098
+ maxPixels
3099
+ );
3103
3100
  const rawPixels = Buffer.allocUnsafe(height * stride);
3104
3101
  const prevRow = new Uint8Array(stride);
3105
3102
  const currRow = new Uint8Array(stride);
@@ -3146,7 +3143,11 @@ function decodePngRaw(buf, caller) {
3146
3143
  return { width, height, bitDepth, colorType, rawPixels };
3147
3144
  }
3148
3145
  function decodePng(buf) {
3149
- const { width, height, bitDepth, colorType, rawPixels } = decodePngRaw(buf, "decodePng");
3146
+ const { width, height, bitDepth, colorType, rawPixels } = decodePngRaw(
3147
+ buf,
3148
+ "decodePng",
3149
+ MAX_SCREENSHOT_PIXELS
3150
+ );
3150
3151
  if (bitDepth !== 8) {
3151
3152
  throw new Error(`decodePng: unsupported bit depth ${bitDepth} (expected 8)`);
3152
3153
  }
@@ -3198,7 +3199,11 @@ function encodePng(width, height, rgba) {
3198
3199
  ]);
3199
3200
  }
3200
3201
  function decodePngToRgb48le(buf) {
3201
- const { width, height, bitDepth, colorType, rawPixels } = decodePngRaw(buf, "decodePngToRgb48le");
3202
+ const { width, height, bitDepth, colorType, rawPixels } = decodePngRaw(
3203
+ buf,
3204
+ "decodePngToRgb48le",
3205
+ MAX_RGB48LE_PIXELS
3206
+ );
3202
3207
  if (bitDepth !== 16) {
3203
3208
  throw new Error(`decodePngToRgb48le: unsupported bit depth ${bitDepth} (expected 16)`);
3204
3209
  }
@@ -3523,6 +3528,11 @@ function resampleRgb48leObjectFit(source, srcW, srcH, dstW, dstH, fit = "fill",
3523
3528
  if (fit === "fill" && srcW === dstW && srcH === dstH) {
3524
3529
  return source;
3525
3530
  }
3531
+ if (dstW * dstH > MAX_RGB48LE_PIXELS) {
3532
+ throw new Error(
3533
+ `resampleRgb48leObjectFit: ${dstW}x${dstH} target exceeds the ${MAX_RGB48LE_PIXELS}-pixel limit`
3534
+ );
3535
+ }
3526
3536
  const pos = parseObjectPosition(objectPosition);
3527
3537
  const rect = computeObjectFitRect(srcW, srcH, dstW, dstH, fit, pos);
3528
3538
  const dst = Buffer.alloc(dstW * dstH * 6);
@@ -4370,7 +4380,7 @@ async function injectResolvedVideoFramesBatch(page, updates, restyleIds) {
4370
4380
  ].map((item) => ({ ...item, frameId: renderFrameIdForRenderId(item.videoId) }));
4371
4381
  return await page.evaluate(
4372
4382
  // fallow-ignore-next-line complexity
4373
- async (items2, visualProperties, colorGradingSourceHiddenAttr) => {
4383
+ async (items2, visualProperties) => {
4374
4384
  const injectedIds = [];
4375
4385
  const pendingDecodes = [];
4376
4386
  const imagesToPublish = [];
@@ -4409,7 +4419,7 @@ async function injectResolvedVideoFramesBatch(page, updates, restyleIds) {
4409
4419
  const isNewImage = !hasImg;
4410
4420
  const computedStyle = window.getComputedStyle(video);
4411
4421
  const opacityParsed = parseFloat(computedStyle.opacity);
4412
- const computedOpacity = video.hasAttribute(colorGradingSourceHiddenAttr) ? 1 : Number.isNaN(opacityParsed) ? 1 : opacityParsed;
4422
+ const computedOpacity = Number.isNaN(opacityParsed) ? 1 : opacityParsed;
4413
4423
  const videoRect = video.getBoundingClientRect();
4414
4424
  const videoBox = {
4415
4425
  left: Number.isFinite(video.offsetLeft) ? video.offsetLeft : 0,
@@ -4479,14 +4489,13 @@ async function injectResolvedVideoFramesBatch(page, updates, restyleIds) {
4479
4489
  return injectedIds;
4480
4490
  },
4481
4491
  items,
4482
- [...MEDIA_VISUAL_STYLE_PROPERTIES],
4483
- COLOR_GRADING_SOURCE_HIDDEN_ATTR
4492
+ [...MEDIA_VISUAL_STYLE_PROPERTIES]
4484
4493
  );
4485
4494
  }
4486
4495
  async function syncVideoFrameVisibility(page, activeVideoIds) {
4487
4496
  await page.evaluate(
4488
4497
  // fallow-ignore-next-line complexity
4489
- (ids, colorGradingSourceHiddenAttr) => {
4498
+ (ids) => {
4490
4499
  const isVisualAncestorHidden = (el) => {
4491
4500
  let parent = el.parentElement;
4492
4501
  while (parent !== null && parent !== document.documentElement) {
@@ -4512,10 +4521,7 @@ async function syncVideoFrameVisibility(page, activeVideoIds) {
4512
4521
  if (visible) {
4513
4522
  video.style.setProperty("visibility", "hidden", "important");
4514
4523
  video.style.setProperty("pointer-events", "none", "important");
4515
- if (hasImg) {
4516
- if (video.hasAttribute(colorGradingSourceHiddenAttr)) img.style.opacity = "1";
4517
- img.style.visibility = "visible";
4518
- }
4524
+ if (hasImg) img.style.visibility = "visible";
4519
4525
  } else {
4520
4526
  video.style.setProperty("visibility", "hidden", "important");
4521
4527
  video.style.setProperty("pointer-events", "none", "important");
@@ -4526,8 +4532,7 @@ async function syncVideoFrameVisibility(page, activeVideoIds) {
4526
4532
  setColorGradingVisibility?.(video, visible);
4527
4533
  }
4528
4534
  },
4529
- activeVideoIds,
4530
- COLOR_GRADING_SOURCE_HIDDEN_ATTR
4535
+ activeVideoIds
4531
4536
  );
4532
4537
  }
4533
4538
 
@@ -5489,12 +5494,12 @@ async function listFfmpeg(flag) {
5489
5494
  // ../engine/src/utils/renderProvenance.ts
5490
5495
  import { readFileSync as readFileSync3 } from "fs";
5491
5496
  import { createRequire } from "module";
5492
- import { dirname as dirname2, join as join6 } from "path";
5497
+ import { dirname as dirname3, join as join6 } from "path";
5493
5498
  import { fileURLToPath as fileURLToPath2 } from "url";
5494
5499
 
5495
5500
  // ../engine/src/utils/ffprobe.ts
5496
5501
  import { spawn as spawn3 } from "child_process";
5497
- import { createReadStream, mkdtempSync as mkdtempSync2, readFileSync as readFileSync2, rmSync, statSync as statSync2 } from "fs";
5502
+ import { createReadStream, mkdtempSync as mkdtempSync2, readFileSync as readFileSync2, rmSync, statSync } from "fs";
5498
5503
  import { StringDecoder as StringDecoder2 } from "string_decoder";
5499
5504
  import { tmpdir as tmpdir3 } from "os";
5500
5505
  import { basename, join as join5 } from "path";
@@ -5507,7 +5512,6 @@ var CA_BUNDLES = [
5507
5512
  "/etc/ssl/cert.pem"
5508
5513
  ];
5509
5514
  var RECONNECT_ARGS = ["-rw_timeout", "30000000", "-reconnect", "1", "-reconnect_delay_max", "2"];
5510
- var SELF_CONTAINED_FORMATS = "mov,matroska,mxf,avi,mpeg,mpegts,mpegvideo,flv,asf,ogg,wav,mp3,aac,flac,aiff,gif,image2,png_pipe,jpeg_pipe,webp_pipe,bmp_pipe,tiff_pipe";
5511
5515
  function selfContainedFormatArgs() {
5512
5516
  return resolveRestrictPageNetwork() ? ["-format_whitelist", SELF_CONTAINED_FORMATS] : [];
5513
5517
  }
@@ -5515,7 +5519,8 @@ function urlInputArgs(input, {
5515
5519
  tool = "ffmpeg",
5516
5520
  caBundles = CA_BUNDLES
5517
5521
  } = {}) {
5518
- if (!/^https:\/\//i.test(input)) return [];
5522
+ const mediaFormats = () => mediaInputFormatArgs(tool === "ffprobe" ? getFfprobeBinary() : getFfmpegBinary());
5523
+ if (!/^https:\/\//i.test(input)) return mediaFormats();
5519
5524
  const caFile = caBundles.find((path) => existsSync4(path));
5520
5525
  if (!caFile) {
5521
5526
  throw new Error(
@@ -5523,7 +5528,7 @@ function urlInputArgs(input, {
5523
5528
  );
5524
5529
  }
5525
5530
  const networkRetry = tool === "ffmpeg" ? ["-reconnect_on_network_error", "1"] : [];
5526
- const renderServiceLimits = resolveRestrictPageNetwork() ? ["-protocol_whitelist", "https,tls,tcp", ...selfContainedFormatArgs()] : [];
5531
+ const renderServiceLimits = resolveRestrictPageNetwork() ? ["-protocol_whitelist", "https,tls,tcp", ...selfContainedFormatArgs()] : mediaFormats();
5527
5532
  return [
5528
5533
  "-tls_verify",
5529
5534
  "1",
@@ -5544,794 +5549,1169 @@ function redactUrlQueriesInError(error) {
5544
5549
  return error;
5545
5550
  }
5546
5551
 
5547
- // ../engine/src/utils/runFfmpeg.ts
5548
- import { spawn as spawn2 } from "child_process";
5549
-
5550
- // ../engine/src/utils/processTracker.ts
5551
- var tracked = /* @__PURE__ */ new Set();
5552
- function trackChildProcess(proc) {
5553
- tracked.add(proc);
5554
- const remove = () => tracked.delete(proc);
5555
- proc.once("exit", remove);
5556
- proc.once("close", remove);
5552
+ // ../engine/src/utils/notMediaPayload.ts
5553
+ import { createHash } from "crypto";
5554
+ import { constants } from "fs";
5555
+ import { open as openFile } from "fs/promises";
5556
+ import { dirname as dirname2, isAbsolute, relative, resolve } from "path";
5557
+ var NOT_MEDIA_PAYLOAD = "NOT_MEDIA_PAYLOAD";
5558
+ var MAX_LISTED_FINGERPRINTS = 8;
5559
+ var NotMediaPayloadError = class extends Error {
5560
+ code = NOT_MEDIA_PAYLOAD;
5561
+ owner = "user";
5562
+ retryable = false;
5563
+ elementFingerprints;
5564
+ constructor(elementFingerprints) {
5565
+ const listed2 = elementFingerprints.slice(0, MAX_LISTED_FINGERPRINTS).join(",");
5566
+ const elided = elementFingerprints.length - MAX_LISTED_FINGERPRINTS;
5567
+ super(
5568
+ `${elementFingerprints.length} media source(s) are text documents (HTML/XML/JSON, or a playlist naming files outside its own folder), not media containers [elements=${listed2}${elided > 0 ? `,+${elided}` : ""}]. Either an unresolved nested-composition preview URL was authored as a media src, or the source answered with an error page or API error body carrying a success status.`
5569
+ );
5570
+ this.name = "NotMediaPayloadError";
5571
+ this.elementFingerprints = elementFingerprints;
5572
+ }
5573
+ };
5574
+ var TextArtMediaError = class extends NotMediaPayloadError {
5575
+ constructor() {
5576
+ super([]);
5577
+ this.message = "Media source is a text file, not a media container";
5578
+ }
5579
+ };
5580
+ function fingerprintElementId(elementId) {
5581
+ return createHash("sha256").update(elementId).digest("hex").slice(0, 16);
5557
5582
  }
5558
- function killTrackedProcesses() {
5559
- const alive = [];
5560
- for (const proc of tracked) {
5561
- if (!proc.killed) {
5562
- try {
5563
- proc.kill("SIGTERM");
5564
- alive.push(proc);
5565
- } catch {
5566
- }
5583
+ var SNIFF_BYTES = 512;
5584
+ var DOCUMENT_OPENING_BYTES = /* @__PURE__ */ new Set([60, 123, 91]);
5585
+ var SKIPPABLE_LEADING_BYTES = /* @__PURE__ */ new Set([0, 9, 10, 11, 12, 13, 32]);
5586
+ var BYTE_ORDER_MARKS = [
5587
+ Buffer.from([239, 187, 191]),
5588
+ // UTF-8
5589
+ Buffer.from([255, 254]),
5590
+ // UTF-16 LE
5591
+ Buffer.from([254, 255])
5592
+ // UTF-16 BE
5593
+ ];
5594
+ function byteOrderMarkLength(head) {
5595
+ for (const mark of BYTE_ORDER_MARKS) {
5596
+ if (head.length >= mark.length && head.subarray(0, mark.length).equals(mark)) {
5597
+ return mark.length;
5567
5598
  }
5568
5599
  }
5569
- tracked.clear();
5570
- if (alive.length === 0) return;
5571
- setTimeout(() => {
5572
- for (const proc of alive) {
5573
- try {
5574
- proc.kill("SIGKILL");
5575
- } catch {
5576
- }
5577
- }
5578
- }, 500).unref();
5600
+ return 0;
5579
5601
  }
5580
-
5581
- // ../engine/src/utils/managedChildProcess.ts
5582
- import { StringDecoder } from "string_decoder";
5583
- var DEFAULT_TERMINATION_GRACE_MS = 2e3;
5584
- var DEFAULT_STDERR_MAX_BYTES = 64 * 1024;
5585
- var RAW_STDERR_SLACK_FACTOR = 2;
5586
- var ManagedChildProcess = class {
5587
- constructor(child, options = {}) {
5588
- this.child = child;
5589
- this.options = options;
5590
- this.now = options.now ?? Date.now;
5591
- this.startedAtMs = this.now();
5592
- this.outcomePromise = new Promise((resolve3) => {
5593
- this.resolveOutcome = resolve3;
5594
- });
5595
- child.stderr?.on("data", this.onStderr);
5596
- child.once("spawn", this.onSpawn);
5597
- child.once("close", this.onClose);
5598
- child.on("error", this.onError);
5599
- this.installAbort();
5600
- this.installDeadline();
5601
- this.markActivity();
5602
+ async function readAt(fh, bytes, position) {
5603
+ const buf = Buffer.alloc(bytes);
5604
+ let filled = 0;
5605
+ while (filled < buf.length) {
5606
+ const { bytesRead } = await fh.read(buf, filled, buf.length - filled, position + filled);
5607
+ if (bytesRead === 0) break;
5608
+ filled += bytesRead;
5602
5609
  }
5603
- child;
5604
- options;
5605
- startedAtMs;
5606
- now;
5607
- outcomePromise;
5608
- resolveOutcome;
5609
- requestedReason = null;
5610
- rawStderrTail = "";
5611
- rawStderrTailCut = false;
5612
- stderrDecoder = new StringDecoder("utf8");
5613
- spawned = false;
5614
- settled = false;
5615
- deadlineTimer = null;
5616
- inactivityTimer = null;
5617
- escalationTimer = null;
5618
- wait() {
5619
- return this.outcomePromise;
5610
+ return buf.subarray(0, filled);
5611
+ }
5612
+ var OPEN_WITHOUT_WAITING = constants.O_RDONLY | (constants.O_NONBLOCK ?? 0);
5613
+ async function openRegular(path) {
5614
+ const fh = await openFile(path, OPEN_WITHOUT_WAITING);
5615
+ try {
5616
+ const stats = await fh.stat();
5617
+ if (stats.isFile() || stats.isDirectory()) return fh;
5618
+ } catch (error) {
5619
+ await fh.close().catch(() => {
5620
+ });
5621
+ throw error;
5620
5622
  }
5621
- get isSettled() {
5622
- return this.settled;
5623
+ await fh.close().catch(() => {
5624
+ });
5625
+ return null;
5626
+ }
5627
+ async function readHead(filePath) {
5628
+ const fh = await openRegular(filePath);
5629
+ if (!fh) return null;
5630
+ try {
5631
+ const { size } = await fh.stat();
5632
+ const first = await readAt(fh, SNIFF_BYTES, 0);
5633
+ const start = await textStart(fh, first);
5634
+ if (start < 0) return null;
5635
+ const head = start === 0 ? first : await readAt(fh, SNIFF_BYTES, start);
5636
+ return { head, fileSize: size - start };
5637
+ } finally {
5638
+ await fh.close().catch(() => {
5639
+ });
5623
5640
  }
5624
- markActivity() {
5625
- if (this.settled || this.options.inactivityTimeoutMs === void 0) return;
5626
- if (this.inactivityTimer) clearTimeout(this.inactivityTimer);
5627
- this.inactivityTimer = setTimeout(
5628
- () => this.requestTermination("inactivity"),
5629
- Math.max(0, this.options.inactivityTimeoutMs)
5630
- );
5631
- this.inactivityTimer.unref?.();
5641
+ }
5642
+ var FIRST_BOX_TYPES = /* @__PURE__ */ new Set([
5643
+ "ftyp",
5644
+ "styp",
5645
+ "free",
5646
+ "skip",
5647
+ "wide",
5648
+ "uuid",
5649
+ "pdin",
5650
+ "moov",
5651
+ "mdat",
5652
+ "moof"
5653
+ ]);
5654
+ var BOX_TYPE = /^[\x21-\x7e\xa9][\x21-\x7e]{3}$/;
5655
+ function boxLength(head, offset) {
5656
+ const size = head.readUInt32BE(offset);
5657
+ if (size !== 1) return size >= 8 ? size : -1;
5658
+ if (offset + 16 > head.length) return -1;
5659
+ const largeSize = Number(head.readBigUInt64BE(offset + 8));
5660
+ return largeSize >= 16 ? largeSize : -1;
5661
+ }
5662
+ function boxEnd(head, offset, fileSize) {
5663
+ if (offset + 8 > head.length || !BOX_TYPE.test(head.toString("latin1", offset + 4, offset + 8))) {
5664
+ return -1;
5632
5665
  }
5633
- onStderr = (data) => {
5634
- const chunk = Buffer.isBuffer(data) ? data : Buffer.from(data);
5635
- const joined = this.rawStderrTail + this.stderrDecoder.write(chunk);
5636
- this.rawStderrTail = lastBytes(joined, RAW_STDERR_SLACK_FACTOR * this.maxBytes);
5637
- if (this.rawStderrTail !== joined) this.rawStderrTailCut = true;
5638
- this.options.onStderr?.(chunk.toString());
5639
- };
5640
- get maxBytes() {
5641
- return this.options.stderrMaxBytes ?? DEFAULT_STDERR_MAX_BYTES;
5666
+ if (head.readUInt32BE(offset) === 0) return fileSize;
5667
+ const length = boxLength(head, offset);
5668
+ return length >= 0 && offset + length <= fileSize ? offset + length : -1;
5669
+ }
5670
+ function opensWithMediaBox(head, fileSize) {
5671
+ if (!FIRST_BOX_TYPES.has(head.toString("latin1", 4, 8))) return false;
5672
+ let offset = boxEnd(head, 0, fileSize);
5673
+ while (offset >= 0 && offset < fileSize && offset + 16 <= head.length) {
5674
+ offset = boxEnd(head, offset, fileSize);
5642
5675
  }
5643
- redactedStderrTail() {
5644
- const raw = this.rawStderrTailCut ? withoutTokenSeveredByCut(this.rawStderrTail) : this.rawStderrTail;
5645
- return lastBytes(redactUrlQueryStrings(raw), this.maxBytes);
5646
- }
5647
- onSpawn = () => {
5648
- this.spawned = true;
5649
- };
5650
- onClose = (exitCode, signal) => {
5651
- this.settle({
5652
- reason: this.requestedReason ?? "exit",
5653
- exitCode,
5654
- signal,
5655
- stderr: this.redactedStderrTail(),
5656
- durationMs: this.now() - this.startedAtMs
5657
- });
5658
- };
5659
- onError = (error) => {
5660
- if (this.spawned) return;
5661
- this.settle({
5662
- reason: "spawn_error",
5663
- exitCode: null,
5664
- signal: null,
5665
- stderr: this.rawStderrTail.length > 0 ? this.redactedStderrTail() : error.message,
5666
- durationMs: this.now() - this.startedAtMs,
5667
- error
5668
- });
5669
- };
5670
- installAbort() {
5671
- const signal = this.options.signal;
5672
- if (!signal) return;
5673
- if (signal.aborted) {
5674
- this.requestTermination("abort");
5675
- return;
5676
- }
5677
- signal.addEventListener("abort", this.onAbort, { once: true });
5676
+ return offset >= 0;
5677
+ }
5678
+ function startsWithDocumentByte(head, fileSize) {
5679
+ if (opensWithMediaBox(head, fileSize)) return false;
5680
+ for (let index = byteOrderMarkLength(head); index < head.length; index++) {
5681
+ const byte = head[index];
5682
+ if (byte === void 0) break;
5683
+ if (SKIPPABLE_LEADING_BYTES.has(byte)) continue;
5684
+ return DOCUMENT_OPENING_BYTES.has(byte);
5678
5685
  }
5679
- onAbort = () => {
5680
- this.requestTermination("abort");
5681
- };
5682
- installDeadline() {
5683
- if (this.options.deadlineAtMs === void 0) return;
5684
- const remainingMs = Math.max(0, this.options.deadlineAtMs - this.now());
5685
- this.deadlineTimer = setTimeout(() => this.requestTermination("deadline"), remainingMs);
5686
- this.deadlineTimer.unref?.();
5686
+ return false;
5687
+ }
5688
+ async function isNotMediaPayload(filePath) {
5689
+ try {
5690
+ const sniffed = await readHead(filePath);
5691
+ return !sniffed || startsWithDocumentByte(sniffed.head, sniffed.fileSize) || await playlistLeavesItsFolder(filePath);
5692
+ } catch {
5693
+ return false;
5687
5694
  }
5688
- requestTermination(reason) {
5689
- if (this.settled || this.requestedReason) return;
5690
- this.requestedReason = reason;
5691
- try {
5692
- this.child.kill("SIGTERM");
5693
- } catch {
5694
- }
5695
- const graceMs = this.options.terminationGraceMs ?? DEFAULT_TERMINATION_GRACE_MS;
5696
- this.escalationTimer = setTimeout(
5697
- () => {
5698
- if (this.settled) return;
5699
- try {
5700
- this.child.kill("SIGKILL");
5701
- } catch {
5702
- }
5703
- },
5704
- Math.max(0, graceMs)
5705
- );
5706
- this.escalationTimer.unref?.();
5695
+ }
5696
+ async function assertMediaPayload(filePath, elementId) {
5697
+ if (await isNotMediaPayload(filePath)) {
5698
+ throw new NotMediaPayloadError([fingerprintElementId(elementId)]);
5707
5699
  }
5708
- settle(outcome) {
5709
- if (this.settled) return;
5710
- this.settled = true;
5711
- this.clearTimers();
5712
- this.options.signal?.removeEventListener("abort", this.onAbort);
5713
- this.child.stderr?.off("data", this.onStderr);
5714
- this.child.off("spawn", this.onSpawn);
5715
- this.child.off("close", this.onClose);
5716
- this.child.off("error", this.onError);
5717
- this.resolveOutcome(outcome);
5700
+ }
5701
+ var IMAGE_SNIFF_BYTES = 64 * 1024;
5702
+ function withoutLeadingBlanks(text) {
5703
+ let at = 0;
5704
+ while (at < text.length && (text[at] === "\0" || /\s/.test(text[at]))) at++;
5705
+ return text.slice(at);
5706
+ }
5707
+ function headText(head) {
5708
+ const [first, second] = head;
5709
+ if (first === 255 && second === 254) return head.subarray(2).toString("utf16le");
5710
+ if (first === 254 && second === 255) {
5711
+ return Buffer.from(head.subarray(2, head.length - head.length % 2)).swap16().toString("utf16le");
5718
5712
  }
5719
- clearTimers() {
5720
- if (this.deadlineTimer) clearTimeout(this.deadlineTimer);
5721
- if (this.inactivityTimer) clearTimeout(this.inactivityTimer);
5722
- if (this.escalationTimer) clearTimeout(this.escalationTimer);
5723
- this.deadlineTimer = null;
5724
- this.inactivityTimer = null;
5725
- this.escalationTimer = null;
5713
+ return head.toString("latin1", byteOrderMarkLength(head));
5714
+ }
5715
+ function afterMarker(text, from, end) {
5716
+ const at = text.indexOf(end, from);
5717
+ return at < 0 ? null : text.slice(at + end.length);
5718
+ }
5719
+ function afterDoctype(text) {
5720
+ for (let at = 9; at < text.length; at++) {
5721
+ if (text[at] === ">") return text.slice(at + 1);
5722
+ if (text[at] === "[") at = text.indexOf("]", at);
5723
+ if (at < 0) return null;
5726
5724
  }
5727
- };
5728
- function lastBytes(text, maxBytes) {
5729
- return Buffer.byteLength(text) > maxBytes ? Buffer.from(text).subarray(-maxBytes).toString() : text;
5725
+ return null;
5730
5726
  }
5731
- function withoutTokenSeveredByCut(text) {
5732
- const firstSpace = text.search(/\s/);
5733
- return firstSpace < 0 ? "" : text.slice(firstSpace);
5727
+ function afterProlog(text) {
5728
+ if (text.startsWith("<?")) return afterMarker(text, 2, "?>");
5729
+ if (text.startsWith("<!--")) return afterMarker(text, 4, "-->");
5730
+ return /^<!doctype\b/i.test(text) ? afterDoctype(text) : null;
5734
5731
  }
5735
-
5736
- // ../engine/src/utils/runFfmpeg.ts
5737
- var FFMPEG_SIGTERM_EXIT_LINE = /^Exiting normally, received signal 15\.?\r?$/m;
5738
- function isExternalFfmpegInterruption(result) {
5739
- if (result.terminationReason !== "exit" || result.exitCode === 0) return false;
5740
- if (result.signal === "SIGTERM") return true;
5741
- return result.exitCode === 255 && FFMPEG_SIGTERM_EXIT_LINE.test(result.stderr);
5732
+ function opensWithSvgRoot(markup, complete) {
5733
+ let rest = withoutLeadingBlanks(markup);
5734
+ for (let next = afterProlog(rest); next !== null; next = afterProlog(rest)) {
5735
+ rest = withoutLeadingBlanks(next);
5736
+ }
5737
+ return /^<svg[\s/>]/i.test(rest) || !complete && /^<[?!]/.test(rest);
5742
5738
  }
5743
- function ffmpegStatsReader(onStats) {
5744
- let rest = "";
5745
- return (chunk) => {
5746
- const lines = (rest + chunk).split(/[\r\n]/);
5747
- rest = lines.pop() ?? "";
5748
- for (const line of lines) {
5749
- const frame = /frame=\s*(\d+)/.exec(line)?.[1];
5750
- const time = /time=\s*(\d+):(\d+):(\d+(?:\.\d+)?)/.exec(line);
5751
- if (frame === void 0 && !time) continue;
5752
- onStats({
5753
- frames: frame === void 0 ? void 0 : Number(frame),
5754
- seconds: time ? Math.round((Number(time[1]) * 3600 + Number(time[2]) * 60 + Number(time[3])) * 100) / 100 : void 0
5739
+ async function isNotImagePayload(filePath) {
5740
+ try {
5741
+ const fh = await openRegular(filePath);
5742
+ if (!fh) return true;
5743
+ try {
5744
+ const start = await textStart(fh, await readAt(fh, SNIFF_BYTES, 0));
5745
+ if (start < 0) return true;
5746
+ const head = await readAt(fh, IMAGE_SNIFF_BYTES, start);
5747
+ const text = withoutLeadingBlanks(headText(head));
5748
+ if (text.startsWith("{") || text.startsWith("[")) return true;
5749
+ return text.startsWith("<") && !opensWithSvgRoot(text, head.length < IMAGE_SNIFF_BYTES);
5750
+ } finally {
5751
+ await fh.close().catch(() => {
5755
5752
  });
5756
5753
  }
5757
- };
5758
- }
5759
- var DEFAULT_TIMEOUT = 3e5;
5760
- var DEFAULT_STDERR_TAIL_LINES = 15;
5761
- function formatWindowsFfmpegExit(exitCode) {
5762
- if (process.platform !== "win32" || exitCode === null) return void 0;
5763
- if (exitCode === 3221225781 || exitCode === -1073741515) {
5764
- const ffmpegPath = getFfmpegBinary();
5765
- return `[FFmpeg] Windows could not start "${ffmpegPath}": 0xC0000135 (STATUS_DLL_NOT_FOUND). A required DLL could not be loaded. Install a working 64-bit Windows FFmpeg build with all required runtime DLLs.`;
5754
+ } catch {
5755
+ return false;
5766
5756
  }
5767
- if (exitCode === 3221225595 || exitCode === -1073741701) {
5768
- return "[FFmpeg] Windows could not start ffmpeg.exe (STATUS_INVALID_IMAGE_FORMAT). The binary may be corrupted or the wrong architecture. Reinstall a 64-bit Windows FFmpeg build.";
5757
+ }
5758
+ var MAX_PLAYLIST_BYTES = 8 * 1024 * 1024;
5759
+ var MAX_PLAYLIST_DEPTH = 8;
5760
+ var HTTP_URL = /^https?:\/\//i;
5761
+ var OTHER_SCHEME = /^[a-z][a-z0-9+.-]+:/i;
5762
+ var DRIVE_PATH = /^[a-z]:[\\/]/i;
5763
+ var MAX_HLS_LINE_BYTES = 4095;
5764
+ var ATTRIBUTE_GAP = /[\t\n\v\f\r ,]/;
5765
+ function hlsEntries(body) {
5766
+ const names = /* @__PURE__ */ new Set();
5767
+ for (const raw of body.replaceAll("\0", "\n").split(/[\r\n]/)) {
5768
+ for (const whole of /* @__PURE__ */ new Set([raw, raw.slice(0, MAX_HLS_LINE_BYTES)])) {
5769
+ const line = whole.replace(/[\t\v\f ]+$/, "");
5770
+ const found = line.startsWith("#") ? attributeUris(line) : [line, line.trim()];
5771
+ for (const name of found) if (name) names.add(name);
5772
+ }
5769
5773
  }
5770
- if (exitCode === 3221225794 || exitCode === -1073741502) {
5771
- return "[FFmpeg] Windows failed while initializing ffmpeg.exe. The binary may be corrupted, blocked, or missing runtime DLLs. Reinstall a 64-bit Windows FFmpeg build.";
5774
+ return [...names];
5775
+ }
5776
+ function attributeUris(line) {
5777
+ const uris = [];
5778
+ let at = line.indexOf(":") + 1;
5779
+ while (at > 0 && at < line.length) {
5780
+ while (at < line.length && ATTRIBUTE_GAP.test(line[at])) at++;
5781
+ const equals = line.indexOf("=", at);
5782
+ if (equals < 0) break;
5783
+ const [value, next] = attributeValue(line, equals + 1);
5784
+ if (line.slice(at, equals).toUpperCase() === "URI") uris.push(value);
5785
+ at = next;
5772
5786
  }
5773
- return void 0;
5787
+ return uris;
5774
5788
  }
5775
- function formatFfmpegError(exitCode, stderr, tailLines = DEFAULT_STDERR_TAIL_LINES) {
5776
- const tail2 = (stderr ?? "").split(/\r?\n/).filter((line) => line.length > 0).slice(-tailLines).join("\n");
5777
- if (exitCode === null) {
5778
- return tail2 ? `[FFmpeg] ${tail2}` : "[FFmpeg] process error";
5789
+ function attributeValue(line, at) {
5790
+ if (line[at] !== '"') {
5791
+ let end = at;
5792
+ while (end < line.length && !ATTRIBUTE_GAP.test(line[end])) end++;
5793
+ return [line.slice(at, end), end];
5779
5794
  }
5780
- const windowsMessage = formatWindowsFfmpegExit(exitCode);
5781
- if (windowsMessage) {
5782
- return tail2 ? `${windowsMessage}
5783
- ffmpeg stderr (tail):
5784
- ${tail2}` : windowsMessage;
5795
+ let value = "";
5796
+ let index = at + 1;
5797
+ for (; index < line.length && line[index] !== '"'; index++) {
5798
+ if (line[index] === "\\") {
5799
+ if (index + 1 >= line.length) break;
5800
+ index++;
5801
+ }
5802
+ value += line[index];
5785
5803
  }
5786
- return tail2 ? `FFmpeg exited with code ${exitCode}
5787
- ffmpeg stderr (tail):
5788
- ${tail2}` : `FFmpeg exited with code ${exitCode}`;
5804
+ return [value, line[index] === '"' ? index + 1 : index];
5789
5805
  }
5790
- function describeFfmpegFailure(result, timeoutMs) {
5791
- const error = formatFfmpegError(result.exitCode, result.stderr);
5792
- if (result.terminationReason === "inactivity") {
5793
- return `FFmpeg timed out after ${timeoutMs} ms without progress (ffmpegProcessTimeout, FFMPEG_PROCESS_TIMEOUT_MS). ${error}`;
5806
+ var UTF8_BOM = "\xEF\xBB\xBF";
5807
+ function playlistEntries(text) {
5808
+ const body = (text.startsWith(UTF8_BOM) ? text.slice(UTF8_BOM.length) : text).trimStart();
5809
+ if (body.startsWith("#EXTM3U")) return hlsEntries(body);
5810
+ if (/^ffconcat\s+version/i.test(body)) {
5811
+ return body.split(/\r?\n/).flatMap((raw) => {
5812
+ const match = /^\s*file\s+(.*)$/.exec(raw);
5813
+ if (!match) return [];
5814
+ const value = match[1].trim();
5815
+ return [value.startsWith("'") ? value.slice(1, -1).replace(/\\(.)/g, "$1") : value];
5816
+ });
5794
5817
  }
5795
- if (result.exitCode !== null) return error;
5796
- const signalOrRequestedStop = result.terminationReason === "exit" ? result.signal : result.terminationReason;
5797
- return signalOrRequestedStop ? `FFmpeg ended without an exit code (${signalOrRequestedStop}). ${error}` : error;
5798
- }
5799
- function spawnFfmpeg(args) {
5800
- const ffmpeg = spawn2(getFfmpegBinary(), args, { windowsHide: true });
5801
- trackChildProcess(ffmpeg);
5802
- return ffmpeg;
5818
+ return void 0;
5803
5819
  }
5804
- function succeeded(outcome) {
5805
- return outcome.reason === "exit" && outcome.exitCode === 0;
5820
+ function entryLeavesFolder(entry, base, folder) {
5821
+ if (HTTP_URL.test(entry)) return false;
5822
+ if (OTHER_SCHEME.test(entry) && !DRIVE_PATH.test(entry)) return true;
5823
+ return [entry, percentDecoded(entry)].some((path) => {
5824
+ if (isAbsolute(path) || DRIVE_PATH.test(path) || path.startsWith("\\")) return true;
5825
+ const inside = relative(folder, resolve(base, path));
5826
+ return inside === ".." || inside.startsWith("../") || inside.startsWith("..\\") || isAbsolute(inside);
5827
+ });
5806
5828
  }
5807
- function toResult(outcome, stderr = outcome.stderr) {
5808
- const result = {
5809
- success: succeeded(outcome),
5810
- exitCode: outcome.exitCode,
5811
- signal: outcome.signal,
5812
- stderr,
5813
- durationMs: outcome.durationMs,
5814
- terminationReason: outcome.reason,
5815
- error: outcome.error
5816
- };
5817
- if (isExternalFfmpegInterruption(result)) {
5818
- result.failureReason = "external_interruption";
5819
- }
5820
- return result;
5829
+ function percentDecoded(value) {
5830
+ return value.replace(
5831
+ /%([0-9a-f]{2})/gi,
5832
+ (_escape, hex) => String.fromCharCode(Number.parseInt(hex, 16))
5833
+ );
5821
5834
  }
5822
- var ABORTED_BEFORE_START = {
5823
- success: false,
5824
- exitCode: null,
5825
- signal: null,
5826
- stderr: "",
5827
- durationMs: 0,
5828
- terminationReason: "abort"
5829
- };
5830
- async function runFfmpeg(args, opts) {
5831
- if (opts?.signal?.aborted) return { ...ABORTED_BEFORE_START };
5832
- let framesWritten = 0;
5833
- let secondsWritten = 0;
5834
- const readStats = ffmpegStatsReader(({ frames = 0, seconds = 0 }) => {
5835
- if (frames <= framesWritten && seconds <= secondsWritten) return;
5836
- framesWritten = Math.max(frames, framesWritten);
5837
- secondsWritten = Math.max(seconds, secondsWritten);
5838
- managed.markActivity();
5839
- });
5840
- const managed = new ManagedChildProcess(spawnFfmpeg(args), {
5841
- signal: opts?.signal,
5842
- inactivityTimeoutMs: opts?.timeout ?? DEFAULT_TIMEOUT,
5843
- onStderr: (chunk) => {
5844
- readStats(chunk);
5845
- opts?.onStderr?.(chunk);
5846
- }
5847
- });
5848
- return toResult(await managed.wait());
5849
- }
5850
-
5851
- // ../engine/src/utils/ffprobe.ts
5852
- var FFPROBE_STDERR_MAX_BYTES = 8 * 1024;
5853
- var FFPROBE_STDOUT_MAX_CHARS = 8e6;
5854
- var FFPROBE_ERROR_MAX_CHARS = 4 * 1024;
5855
- function redactFfprobeInput(stderr, filePath) {
5856
- if (!filePath) return stderr;
5857
- let redacted = stderr.split(filePath).join("[input]");
5858
- const inputBasename = basename(filePath);
5859
- if (inputBasename) redacted = redacted.split(inputBasename).join("[input]");
5860
- if (!redacted.startsWith("[input]")) {
5861
- for (let offset = 1; offset < filePath.length; offset += 1) {
5862
- const suffix = filePath.slice(offset);
5863
- if (suffix.length < 4 || !redacted.startsWith(suffix)) continue;
5864
- const boundary = redacted[suffix.length];
5865
- if (boundary !== void 0 && !/[\s:'")\]}]/.test(boundary)) continue;
5866
- redacted = `[input]${redacted.slice(suffix.length)}`;
5867
- break;
5868
- }
5869
- }
5870
- return redacted;
5871
- }
5872
- function sanitizeFfprobeDiagnostic(stderr, filePath) {
5873
- const stderrWithoutInput = redactFfprobeInput(stderr, filePath);
5874
- const redacted = redactTelemetryString(stderrWithoutInput, FFPROBE_STDERR_MAX_BYTES);
5875
- if (redacted.length <= FFPROBE_ERROR_MAX_CHARS) return redacted;
5876
- return `\u2026${redacted.slice(-(FFPROBE_ERROR_MAX_CHARS - 1))}`;
5877
- }
5878
- async function runFfprobe(filePath, argsWithoutInput, signal, stdoutOptions) {
5879
- if (filePath === "-") {
5880
- throw new Error('[FFmpeg] Refusing to probe "-": stdin is not a supported input path.');
5881
- }
5882
- const command = getFfprobeBinary();
5883
- const args = [
5884
- "-v",
5885
- "error",
5886
- ...urlInputArgs(filePath, { tool: "ffprobe" }),
5887
- ...argsWithoutInput,
5888
- "--",
5889
- filePath
5890
- ];
5891
- const proc = spawn3(command, args, {
5892
- // Nothing is ever written to the child's stdin; leaving it as a pipe is
5893
- // what lets a stdin-reading invocation block indefinitely.
5894
- stdio: ["ignore", "pipe", "pipe"],
5895
- // See runFfmpeg.ts: keeps a console window off the user's desktop on Windows.
5896
- windowsHide: true
5897
- });
5898
- trackChildProcess(proc);
5899
- const decoder = new StringDecoder2("utf8");
5900
- let stdout = "";
5901
- let stdoutTruncated = false;
5902
- const stdoutMaxChars = stdoutOptions?.maxChars ?? FFPROBE_STDOUT_MAX_CHARS;
5903
- proc.stdout.on("data", (data) => {
5904
- if (stdoutTruncated) return;
5905
- stdout += decoder.write(data);
5906
- if (stdout.length > stdoutMaxChars) {
5907
- if (stdoutOptions?.retainTail) {
5908
- stdout = stdout.slice(-stdoutMaxChars);
5909
- } else {
5910
- stdoutTruncated = true;
5911
- stdout = "";
5912
- }
5913
- }
5914
- });
5915
- const managed = new ManagedChildProcess(proc, {
5916
- signal,
5917
- deadlineAtMs: Date.now() + 3e4,
5918
- stderrMaxBytes: FFPROBE_STDERR_MAX_BYTES
5919
- });
5920
- const outcome = await managed.wait();
5921
- stdout += decoder.end();
5922
- if (stdoutTruncated) {
5923
- throw new Error(
5924
- `[FFmpeg] ffprobe output exceeded ${stdoutMaxChars} characters; refusing to parse a truncated result.`
5925
- );
5926
- }
5927
- if (outcome.reason === "spawn_error") {
5928
- if (outcome.error?.code === "ENOENT") {
5929
- const configured = process.env[FFPROBE_PATH_ENV]?.trim();
5930
- throw new Error(
5931
- configured ? `[FFmpeg] ffprobe not found at ${FFPROBE_PATH_ENV}="${configured}". Please install FFmpeg.` : "[FFmpeg] ffprobe not found. Please install FFmpeg."
5932
- );
5933
- }
5934
- throw outcome.error ?? new Error(outcome.stderr);
5935
- }
5936
- if (outcome.reason !== "exit" || outcome.exitCode !== 0) {
5937
- const diagnostic = sanitizeFfprobeDiagnostic(outcome.stderr, filePath);
5938
- throw new Error(
5939
- `[FFmpeg] ffprobe ${outcome.reason} with code ${outcome.exitCode}: ${diagnostic}`
5940
- );
5941
- }
5942
- return stdout;
5943
- }
5944
- function parseProbeJson(stdout) {
5945
- try {
5946
- return JSON.parse(stdout);
5947
- } catch (e) {
5948
- throw new Error(
5949
- `[FFmpeg] Failed to parse ffprobe output: ${e instanceof Error ? e.message : e}`
5950
- );
5951
- }
5952
- }
5953
- var videoMetadataCache = /* @__PURE__ */ new Map();
5954
- var finalVideoFrameTimestampCache = /* @__PURE__ */ new Map();
5955
- var finalVideoFrameTimestampSignalCaches = /* @__PURE__ */ new WeakMap();
5956
- var audioMetadataCache = /* @__PURE__ */ new Map();
5957
- var audioMetadataSignalCaches = /* @__PURE__ */ new WeakMap();
5958
- var mediaProbeOutputCache = /* @__PURE__ */ new Map();
5959
- var mediaProbeOutputSignalCaches = /* @__PURE__ */ new WeakMap();
5960
- var MEDIA_PROBE_OUTPUT_CACHE_MAX_ENTRIES = 128;
5961
- var AUDIO_DURATION_PROBE_MARGIN_SECONDS = 0.05;
5962
- var AUDIO_DURATION_PROBE_TAIL_SECONDS = 1;
5963
- var FFPROBE_READ_INTERVAL_EXPLICIT_FAR_END = "+2147483647";
5964
- var STILL_IMAGE_DEMUXERS = /* @__PURE__ */ new Set([
5965
- "apng",
5966
- "bmp_pipe",
5967
- "dds_pipe",
5968
- "dpx_pipe",
5969
- "exr_pipe",
5970
- "gif",
5971
- "ico",
5972
- "image2",
5973
- "image2pipe",
5974
- "jpeg_pipe",
5975
- "jxl_pipe",
5976
- "png_pipe",
5977
- "qdraw_pipe",
5978
- "sgi_pipe",
5979
- "svg_pipe",
5980
- "tiff_pipe",
5981
- "webp_pipe"
5982
- ]);
5983
- async function hasAvifFileBrand(filePath) {
5835
+ var asBytes = (path) => Buffer.from(path).toString("latin1");
5836
+ async function playlistLeavesItsFolder(filePath, placedAt = filePath) {
5837
+ const placed = asBytes(resolve(placedAt));
5838
+ const walk = { folder: dirname2(placed), seen: /* @__PURE__ */ new Set(), verdicts: /* @__PURE__ */ new Map() };
5984
5839
  try {
5985
- const chunks = [];
5986
- for await (const chunk of createReadStream(filePath, { start: 0, end: 4095 })) {
5987
- chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
5988
- }
5989
- const bytes = Buffer.concat(chunks);
5990
- if (bytes.length < 16 || bytes.toString("ascii", 4, 8) !== "ftyp") return false;
5991
- const boxSize = bytes.readUInt32BE(0);
5992
- if (boxSize < 16 || boxSize > bytes.length) return false;
5993
- const avifBrands = /* @__PURE__ */ new Set(["avif", "avis"]);
5994
- if (avifBrands.has(bytes.toString("ascii", 8, 12))) return true;
5995
- for (let offset = 16; offset + 4 <= boxSize; offset += 4) {
5996
- if (avifBrands.has(bytes.toString("ascii", offset, offset + 4))) return true;
5997
- }
5998
- return false;
5840
+ return await listLeaves(asBytes(resolve(filePath)), placed, walk, 0);
5999
5841
  } catch {
6000
5842
  return false;
6001
5843
  }
6002
5844
  }
6003
- async function isStillImageVisual(output, filePath) {
6004
- const formatNames = (output.format.format_name ?? "").split(",").map((name) => name.trim().toLowerCase()).filter(Boolean);
6005
- return formatNames.some((name) => STILL_IMAGE_DEMUXERS.has(name)) || await hasAvifFileBrand(filePath);
5845
+ var MAX_ID3_TAGS = 16;
5846
+ function isId3Header(head) {
5847
+ return head.length >= 10 && head.toString("latin1", 0, 3) === "ID3" && head[3] !== 255 && head[4] !== 255 && head.subarray(6, 10).every((byte) => byte < 128);
6006
5848
  }
6007
- function isPngImageProbe(output) {
6008
- const formatNames = (output.format.format_name ?? "").split(",").map((name) => name.trim().toLowerCase());
6009
- return formatNames.includes("png_pipe") || output.streams.some(
6010
- (stream) => stream.codec_type === "video" && stream.codec_name?.toLowerCase() === "png"
6011
- );
5849
+ async function textStart(fh, first) {
5850
+ let offset = 0;
5851
+ let head = first;
5852
+ for (let tags = 0; tags <= MAX_ID3_TAGS; tags++) {
5853
+ if (!isId3Header(head)) return offset;
5854
+ const size = head[6] << 21 | head[7] << 14 | head[8] << 7 | head[9];
5855
+ offset += 10 + size + (head[5] & 16 ? 10 : 0);
5856
+ head = await readAt(fh, 10, offset);
5857
+ }
5858
+ return -1;
6012
5859
  }
6013
- var contentAddressedUrls = /* @__PURE__ */ new Map();
6014
- var withoutQuery = (url) => url.split(/[?#]/, 1)[0] ?? url;
6015
- function declareContentAddressedUrl(url, sha256) {
6016
- contentAddressedUrls.set(withoutQuery(url), sha256);
5860
+ var MANIFEST_SIGNATURE = /^<(\?xml|MPD\b|!DOCTYPE|html\b|SmoothStreamingMedia\b)/i;
5861
+ function opensAsManifest(head) {
5862
+ return MANIFEST_SIGNATURE.test(withoutLeadingBlanks(headText(head)));
6017
5863
  }
6018
- var probeFactsUrls = /* @__PURE__ */ new Map();
6019
- function declareProbeFactsUrl(url, factsUrl) {
6020
- probeFactsUrls.set(withoutQuery(url), factsUrl);
5864
+ function startsAsPlaylist(head) {
5865
+ const text = head.toString("utf8").replace(/^\uFEFF/, "").trimStart();
5866
+ return text.startsWith("#EXTM3U") || /^ffconcat\s+version/i.test(text);
6021
5867
  }
6022
- function mediaFileIdentity(filePath) {
6023
- if (/^https?:\/\//i.test(filePath)) {
6024
- const sha256 = contentAddressedUrls.get(withoutQuery(filePath));
6025
- return sha256 ? `sha256:${sha256}` : null;
6026
- }
5868
+ async function readList(path, nested) {
5869
+ const fh = await openRegular(Buffer.from(path, "latin1"));
5870
+ if (!fh) return true;
6027
5871
  try {
6028
- const stat = statSync2(filePath, { bigint: true });
6029
- return [stat.dev, stat.ino, stat.size, stat.mtimeNs, stat.ctimeNs].join(":");
6030
- } catch {
6031
- return null;
5872
+ const first = await readAt(fh, SNIFF_BYTES, 0);
5873
+ const start = await textStart(fh, first);
5874
+ if (start < 0) return true;
5875
+ const head = start === 0 ? first : await readAt(fh, SNIFF_BYTES, start);
5876
+ if (!startsAsPlaylist(head)) return nested && opensAsManifest(head) ? true : null;
5877
+ const body = await readAt(fh, MAX_PLAYLIST_BYTES + 1, start);
5878
+ return body.length > MAX_PLAYLIST_BYTES ? true : body.toString("latin1");
5879
+ } finally {
5880
+ await fh.close().catch(() => {
5881
+ });
6032
5882
  }
6033
5883
  }
6034
- function readMetadataCache(cache, key, identity) {
6035
- const cached = cache.get(key);
6036
- return cached?.identity === identity ? cached.promise : void 0;
6037
- }
6038
- function writeMetadataCache(cache, key, identity, promise) {
6039
- const entry = { identity, promise };
6040
- cache.set(key, entry);
6041
- void promise.then(
6042
- () => {
6043
- if (identity === null && cache.get(key) === entry) cache.delete(key);
6044
- },
6045
- () => {
6046
- if (cache.get(key) === entry) cache.delete(key);
6047
- }
5884
+ var isMissing = (error) => ["ENOENT", "ENOTDIR", "ENAMETOOLONG"].includes(
5885
+ error?.code ?? ""
5886
+ );
5887
+ async function listLeaves(readPath, path, walk, depth) {
5888
+ const text = await readList(readPath, depth > 0).catch(
5889
+ (error) => depth > 0 && !isMissing(error) ? true : null
6048
5890
  );
5891
+ if (text === null) return false;
5892
+ if (text === true || depth >= MAX_PLAYLIST_DEPTH) return true;
5893
+ if (walk.seen.has(path)) return false;
5894
+ walk.seen.add(path);
5895
+ for (const entry of playlistEntries(text) ?? []) {
5896
+ if (await entryLeaves(entry, dirname2(path), walk, depth)) return true;
5897
+ }
5898
+ return false;
6049
5899
  }
6050
- var PROBE_FACTS_VERSION = "v2";
6051
- var PROBE_JSON_ARGS = ["-print_format", "json", "-show_format", "-show_streams"];
6052
- var storedFacts = /* @__PURE__ */ new Map();
6053
- function readStoredFacts(filePath) {
6054
- if (!/^https?:\/\//i.test(filePath)) return void 0;
6055
- const factsUrl = probeFactsUrls.get(withoutQuery(filePath));
6056
- if (!factsUrl) return void 0;
6057
- let facts = storedFacts.get(factsUrl);
6058
- if (!facts) {
6059
- facts = (async () => {
5900
+ async function entryLeaves(entry, base, walk, depth) {
5901
+ if (entryLeavesFolder(entry, base, walk.folder)) return true;
5902
+ if (HTTP_URL.test(entry)) return false;
5903
+ for (const local of /* @__PURE__ */ new Set([entry, percentDecoded(entry)])) {
5904
+ const nested = resolve(base, local);
5905
+ if (isPrivateFileUnder(walk.folder, nested, isStudioPrivatePath)) return true;
5906
+ let verdict = walk.verdicts.get(nested);
5907
+ if (verdict === void 0) {
5908
+ verdict = await listLeaves(nested, nested, walk, depth + 1);
5909
+ walk.verdicts.set(nested, verdict);
5910
+ }
5911
+ if (verdict) return true;
5912
+ }
5913
+ return false;
5914
+ }
5915
+
5916
+ // ../engine/src/utils/runFfmpeg.ts
5917
+ import { spawn as spawn2 } from "child_process";
5918
+
5919
+ // ../engine/src/utils/processTracker.ts
5920
+ var tracked = /* @__PURE__ */ new Set();
5921
+ function trackChildProcess(proc) {
5922
+ tracked.add(proc);
5923
+ const remove = () => tracked.delete(proc);
5924
+ proc.once("exit", remove);
5925
+ proc.once("close", remove);
5926
+ }
5927
+ function killTrackedProcesses() {
5928
+ const alive = [];
5929
+ for (const proc of tracked) {
5930
+ if (!proc.killed) {
6060
5931
  try {
6061
- const response = await fetch(factsUrl, { signal: AbortSignal.timeout(1e4) });
6062
- if (!response.ok) return null;
6063
- const parsed = JSON.parse(await response.text());
6064
- return Array.isArray(parsed.ffprobe?.streams) ? parsed : null;
5932
+ proc.kill("SIGTERM");
5933
+ alive.push(proc);
6065
5934
  } catch {
6066
- return null;
6067
5935
  }
6068
- })();
6069
- storedFacts.set(factsUrl, facts);
5936
+ }
6070
5937
  }
6071
- return facts;
6072
- }
6073
- function readProbeJson(filePath, signal) {
6074
- const pending = readStoredFacts(filePath);
6075
- if (!pending) return runFfprobe(filePath, PROBE_JSON_ARGS, signal);
6076
- return pending.then(
6077
- (stored) => stored ? JSON.stringify(stored.ffprobe) : runFfprobe(filePath, PROBE_JSON_ARGS, signal)
6078
- );
5938
+ tracked.clear();
5939
+ if (alive.length === 0) return;
5940
+ setTimeout(() => {
5941
+ for (const proc of alive) {
5942
+ try {
5943
+ proc.kill("SIGKILL");
5944
+ } catch {
5945
+ }
5946
+ }
5947
+ }, 500).unref();
6079
5948
  }
6080
- var runtimeFfprobeMajor;
6081
- function ffprobeMajor() {
6082
- runtimeFfprobeMajor ??= new Promise((resolve3) => {
6083
- let out = "";
6084
- const binary = getFfprobeBinary();
6085
- const proc = spawn3(binary, ["-version"], {
6086
- stdio: ["ignore", "pipe", "ignore"],
6087
- windowsHide: true
5949
+
5950
+ // ../engine/src/utils/managedChildProcess.ts
5951
+ import { StringDecoder } from "string_decoder";
5952
+ var DEFAULT_TERMINATION_GRACE_MS = 2e3;
5953
+ var DEFAULT_STDERR_MAX_BYTES = 64 * 1024;
5954
+ var RAW_STDERR_SLACK_FACTOR = 2;
5955
+ var ManagedChildProcess = class {
5956
+ constructor(child, options = {}) {
5957
+ this.child = child;
5958
+ this.options = options;
5959
+ this.now = options.now ?? Date.now;
5960
+ this.startedAtMs = this.now();
5961
+ this.outcomePromise = new Promise((resolve3) => {
5962
+ this.resolveOutcome = resolve3;
6088
5963
  });
6089
- proc.stdout.on("data", (chunk) => out += String(chunk));
6090
- proc.on("error", () => resolve3(void 0));
6091
- proc.on("close", () => resolve3(Number(/version n?(\d+)/.exec(out)?.[1]) || void 0));
6092
- });
6093
- return runtimeFfprobeMajor;
6094
- }
6095
- async function buildProbeFactsText(filePath, signal) {
6096
- const facts = {
6097
- ffprobe: parseProbeJson(await runFfprobe(filePath, PROBE_JSON_ARGS, signal)),
6098
- ffprobeMajor: await ffprobeMajor()
5964
+ child.stderr?.on("data", this.onStderr);
5965
+ child.once("spawn", this.onSpawn);
5966
+ child.once("close", this.onClose);
5967
+ child.on("error", this.onError);
5968
+ this.installAbort();
5969
+ this.installDeadline();
5970
+ this.markActivity();
5971
+ }
5972
+ child;
5973
+ options;
5974
+ startedAtMs;
5975
+ now;
5976
+ outcomePromise;
5977
+ resolveOutcome;
5978
+ requestedReason = null;
5979
+ rawStderrTail = "";
5980
+ rawStderrTailCut = false;
5981
+ stderrDecoder = new StringDecoder("utf8");
5982
+ spawned = false;
5983
+ settled = false;
5984
+ deadlineTimer = null;
5985
+ inactivityTimer = null;
5986
+ escalationTimer = null;
5987
+ wait() {
5988
+ return this.outcomePromise;
5989
+ }
5990
+ get isSettled() {
5991
+ return this.settled;
5992
+ }
5993
+ markActivity() {
5994
+ if (this.settled || this.options.inactivityTimeoutMs === void 0) return;
5995
+ if (this.inactivityTimer) clearTimeout(this.inactivityTimer);
5996
+ this.inactivityTimer = setTimeout(
5997
+ () => this.requestTermination("inactivity"),
5998
+ Math.max(0, this.options.inactivityTimeoutMs)
5999
+ );
6000
+ this.inactivityTimer.unref?.();
6001
+ }
6002
+ onStderr = (data) => {
6003
+ const chunk = Buffer.isBuffer(data) ? data : Buffer.from(data);
6004
+ const joined = this.rawStderrTail + this.stderrDecoder.write(chunk);
6005
+ this.rawStderrTail = lastBytes(joined, RAW_STDERR_SLACK_FACTOR * this.maxBytes);
6006
+ if (this.rawStderrTail !== joined) this.rawStderrTailCut = true;
6007
+ this.options.onStderr?.(chunk.toString());
6099
6008
  };
6100
- try {
6101
- const metadata = await extractMediaMetadata(filePath);
6102
- const window2 = resolveStreamWindow(filePath, {
6103
- videoStreamStartSeconds: metadata.videoStreamStartSeconds,
6104
- videoStreamDurationSeconds: resolvePlayableVideoDuration(metadata) - (metadata.videoStreamLeadSeconds ?? 0)
6105
- });
6106
- if (window2.videoStreamDurationSeconds > 0) {
6107
- facts.finalFrame = {
6108
- streamStart: window2.videoStreamStartSeconds,
6109
- streamDuration: window2.videoStreamDurationSeconds,
6110
- seconds: await extractFinalVideoFrameTimestamp(filePath, window2, signal),
6111
- lastPacketSeconds: await extractFinalPacketDuration(filePath, window2, signal)
6112
- };
6113
- }
6114
- } catch {
6115
- if (signal?.aborted) throw signal.reason;
6009
+ get maxBytes() {
6010
+ return this.options.stderrMaxBytes ?? DEFAULT_STDERR_MAX_BYTES;
6116
6011
  }
6117
- return JSON.stringify(facts);
6118
- }
6119
- function videoStartOnMediaTimeline(metadata) {
6120
- return (metadata.videoStreamLeadSeconds ?? 0) + (metadata.mediaTimeOffsetSeconds ?? 0);
6121
- }
6122
- function formatFfmpegSeconds(seconds) {
6123
- const text = String(seconds);
6124
- return text.includes("e") ? String(+seconds.toFixed(6)) : text;
6125
- }
6126
- function readIntervalSpec(startSeconds, end) {
6127
- const to = typeof end === "number" ? formatFfmpegSeconds(end) : end;
6128
- return `${formatFfmpegSeconds(startSeconds)}%${to}`;
6129
- }
6130
- function ffmpegSeekSeconds(metadata, mediaTime) {
6131
- return mediaTime - (metadata.mediaTimeOffsetSeconds ?? 0);
6132
- }
6133
- function resolvePlayableVideoDuration(metadata) {
6134
- return Number.isFinite(metadata.videoStreamDurationSeconds) && metadata.videoStreamDurationSeconds > 0 ? (metadata.videoStreamLeadSeconds ?? 0) + metadata.videoStreamDurationSeconds : metadata.durationSeconds;
6135
- }
6136
- async function probeMediaOutput(filePath, signal) {
6137
- let cache = mediaProbeOutputCache;
6138
- if (signal) {
6139
- cache = mediaProbeOutputSignalCaches.get(signal) ?? /* @__PURE__ */ new Map();
6140
- mediaProbeOutputSignalCaches.set(signal, cache);
6012
+ redactedStderrTail() {
6013
+ const raw = this.rawStderrTailCut ? withoutTokenSeveredByCut(this.rawStderrTail) : this.rawStderrTail;
6014
+ return lastBytes(redactUrlQueryStrings(raw), this.maxBytes);
6141
6015
  }
6142
- const identity = mediaFileIdentity(filePath);
6143
- const cached = cache.get(filePath);
6144
- if (identity !== null && cached?.identity === identity) {
6145
- if (!signal) {
6146
- cache.delete(filePath);
6147
- cache.set(filePath, cached);
6016
+ onSpawn = () => {
6017
+ this.spawned = true;
6018
+ };
6019
+ onClose = (exitCode, signal) => {
6020
+ this.settle({
6021
+ reason: this.requestedReason ?? "exit",
6022
+ exitCode,
6023
+ signal,
6024
+ stderr: this.redactedStderrTail(),
6025
+ durationMs: this.now() - this.startedAtMs
6026
+ });
6027
+ };
6028
+ onError = (error) => {
6029
+ if (this.spawned) return;
6030
+ this.settle({
6031
+ reason: "spawn_error",
6032
+ exitCode: null,
6033
+ signal: null,
6034
+ stderr: this.rawStderrTail.length > 0 ? this.redactedStderrTail() : error.message,
6035
+ durationMs: this.now() - this.startedAtMs,
6036
+ error
6037
+ });
6038
+ };
6039
+ installAbort() {
6040
+ const signal = this.options.signal;
6041
+ if (!signal) return;
6042
+ if (signal.aborted) {
6043
+ this.requestTermination("abort");
6044
+ return;
6148
6045
  }
6149
- return cached.promise;
6046
+ signal.addEventListener("abort", this.onAbort, { once: true });
6150
6047
  }
6151
- const promise = readProbeJson(filePath, signal).then(parseProbeJson);
6152
- if (identity !== null) {
6153
- cache.set(filePath, { identity, promise });
6154
- if (!signal && cache.size > MEDIA_PROBE_OUTPUT_CACHE_MAX_ENTRIES) {
6155
- const oldestPath = cache.keys().next().value;
6156
- if (oldestPath !== void 0) cache.delete(oldestPath);
6157
- }
6048
+ onAbort = () => {
6049
+ this.requestTermination("abort");
6050
+ };
6051
+ installDeadline() {
6052
+ if (this.options.deadlineAtMs === void 0) return;
6053
+ const remainingMs = Math.max(0, this.options.deadlineAtMs - this.now());
6054
+ this.deadlineTimer = setTimeout(() => this.requestTermination("deadline"), remainingMs);
6055
+ this.deadlineTimer.unref?.();
6158
6056
  }
6159
- promise.catch(() => {
6160
- if (cache.get(filePath)?.promise === promise) {
6161
- cache.delete(filePath);
6057
+ requestTermination(reason) {
6058
+ if (this.settled || this.requestedReason) return;
6059
+ this.requestedReason = reason;
6060
+ try {
6061
+ this.child.kill("SIGTERM");
6062
+ } catch {
6162
6063
  }
6163
- });
6164
- return promise;
6165
- }
6166
- var StructurallyIncompletePngError = class extends Error {
6167
- };
6168
- async function readFileRange(filePath, start, length, signal) {
6169
- const chunks = [];
6170
- for await (const chunk of createReadStream(filePath, {
6171
- start,
6172
- end: start + length - 1,
6173
- highWaterMark: length,
6174
- signal
6175
- })) {
6176
- chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
6064
+ const graceMs = this.options.terminationGraceMs ?? DEFAULT_TERMINATION_GRACE_MS;
6065
+ this.escalationTimer = setTimeout(
6066
+ () => {
6067
+ if (this.settled) return;
6068
+ try {
6069
+ this.child.kill("SIGKILL");
6070
+ } catch {
6071
+ }
6072
+ },
6073
+ Math.max(0, graceMs)
6074
+ );
6075
+ this.escalationTimer.unref?.();
6177
6076
  }
6178
- return Buffer.concat(chunks);
6179
- }
6180
- async function hasCompletePngStructure(filePath, signal) {
6181
- try {
6182
- signal?.throwIfAborted();
6183
- const fileSize = statSync2(filePath).size;
6184
- const signature = await readFileRange(filePath, 0, 8, signal);
6185
- signal?.throwIfAborted();
6186
- if (signature.length !== 8 || !signature.equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]))) {
6187
- return false;
6188
- }
6189
- let seenHeader = false;
6190
- let seenImageData = false;
6191
- let offset = 8;
6192
- while (offset + 12 <= fileSize) {
6193
- signal?.throwIfAborted();
6194
- const chunkHeader = await readFileRange(filePath, offset, 8, signal);
6195
- signal?.throwIfAborted();
6196
- if (chunkHeader.length !== 8) return false;
6197
- const chunkLength = chunkHeader.readUInt32BE(0);
6198
- const chunkEnd = offset + 12 + chunkLength;
6199
- if (chunkEnd > fileSize) return false;
6200
- const chunkType = chunkHeader.toString("ascii", 4, 8);
6201
- if (chunkType === "IHDR") seenHeader = chunkLength === 13 && offset === 8;
6202
- if (chunkType === "IDAT") seenImageData = true;
6203
- if (chunkType === "IEND") return seenHeader && seenImageData && chunkLength === 0;
6204
- offset = chunkEnd;
6205
- }
6206
- return false;
6207
- } catch (error) {
6208
- if (signal?.aborted) throw signal.reason ?? error;
6209
- return false;
6077
+ settle(outcome) {
6078
+ if (this.settled) return;
6079
+ this.settled = true;
6080
+ this.clearTimers();
6081
+ this.options.signal?.removeEventListener("abort", this.onAbort);
6082
+ this.child.stderr?.off("data", this.onStderr);
6083
+ this.child.off("spawn", this.onSpawn);
6084
+ this.child.off("close", this.onClose);
6085
+ this.child.off("error", this.onError);
6086
+ this.resolveOutcome(outcome);
6087
+ }
6088
+ clearTimers() {
6089
+ if (this.deadlineTimer) clearTimeout(this.deadlineTimer);
6090
+ if (this.inactivityTimer) clearTimeout(this.inactivityTimer);
6091
+ if (this.escalationTimer) clearTimeout(this.escalationTimer);
6092
+ this.deadlineTimer = null;
6093
+ this.inactivityTimer = null;
6094
+ this.escalationTimer = null;
6210
6095
  }
6096
+ };
6097
+ function lastBytes(text, maxBytes) {
6098
+ return Buffer.byteLength(text) > maxBytes ? Buffer.from(text).subarray(-maxBytes).toString() : text;
6211
6099
  }
6212
- async function probeMediaProfile(filePath, options) {
6213
- try {
6214
- const output = await probeMediaOutput(filePath, options?.signal);
6215
- options?.signal?.throwIfAborted();
6216
- const videoStreams = output.streams.filter((stream) => stream.codec_type === "video");
6217
- const hasMovingVideoStream = videoStreams.some(
6218
- (stream) => stream.disposition?.attached_pic !== 1
6219
- );
6220
- const isStillImage = videoStreams.length > 0 && await isStillImageVisual(output, filePath);
6221
- options?.signal?.throwIfAborted();
6222
- if (isStillImage && isPngImageProbe(output) && !await hasCompletePngStructure(filePath, options?.signal)) {
6223
- throw new StructurallyIncompletePngError("[FFmpeg] PNG input is structurally incomplete");
6224
- }
6225
- return {
6226
- hasVideoStream: videoStreams.length > 0,
6227
- hasAudioStream: decodableAudioStream(output.streams) !== null,
6228
- visualKind: isStillImage ? "still" : hasMovingVideoStream ? "moving" : "none"
6229
- };
6230
- } catch (error) {
6231
- if (options?.signal?.aborted) throw options.signal.reason ?? error;
6232
- if (error instanceof StructurallyIncompletePngError) throw error;
6233
- const stillImage = extractStillImageMetadata(filePath);
6234
- if (stillImage && await hasCompletePngStructure(filePath, options?.signal)) {
6235
- return { hasVideoStream: true, hasAudioStream: false, visualKind: "still" };
6100
+ function withoutTokenSeveredByCut(text) {
6101
+ const firstSpace = text.search(/\s/);
6102
+ return firstSpace < 0 ? "" : text.slice(firstSpace);
6103
+ }
6104
+
6105
+ // ../engine/src/utils/runFfmpeg.ts
6106
+ var FFMPEG_SIGTERM_EXIT_LINE = /^Exiting normally, received signal 15\.?\r?$/m;
6107
+ function isExternalFfmpegInterruption(result) {
6108
+ if (result.terminationReason !== "exit" || result.exitCode === 0) return false;
6109
+ if (result.signal === "SIGTERM") return true;
6110
+ return result.exitCode === 255 && FFMPEG_SIGTERM_EXIT_LINE.test(result.stderr);
6111
+ }
6112
+ function ffmpegStatsReader(onStats) {
6113
+ let rest = "";
6114
+ return (chunk) => {
6115
+ const lines = (rest + chunk).split(/[\r\n]/);
6116
+ rest = lines.pop() ?? "";
6117
+ for (const line of lines) {
6118
+ const frame = /frame=\s*(\d+)/.exec(line)?.[1];
6119
+ const time = /time=\s*(\d+):(\d+):(\d+(?:\.\d+)?)/.exec(line);
6120
+ if (frame === void 0 && !time) continue;
6121
+ onStats({
6122
+ frames: frame === void 0 ? void 0 : Number(frame),
6123
+ seconds: time ? Math.round((Number(time[1]) * 3600 + Number(time[2]) * 60 + Number(time[3])) * 100) / 100 : void 0
6124
+ });
6236
6125
  }
6237
- throw error;
6238
- }
6126
+ };
6239
6127
  }
6240
- function extractPngMetadataFromBuffer(buf) {
6241
- if (buf.length < 8 || buf[0] !== 137 || buf[1] !== 80 || buf[2] !== 78 || buf[3] !== 71 || buf[4] !== 13 || buf[5] !== 10 || buf[6] !== 26 || buf[7] !== 10) {
6242
- return null;
6128
+ var DEFAULT_TIMEOUT = 3e5;
6129
+ var DEFAULT_STDERR_TAIL_LINES = 15;
6130
+ function formatWindowsFfmpegExit(exitCode) {
6131
+ if (process.platform !== "win32" || exitCode === null) return void 0;
6132
+ if (exitCode === 3221225781 || exitCode === -1073741515) {
6133
+ const ffmpegPath = getFfmpegBinary();
6134
+ return `[FFmpeg] Windows could not start "${ffmpegPath}": 0xC0000135 (STATUS_DLL_NOT_FOUND). A required DLL could not be loaded. Install a working 64-bit Windows FFmpeg build with all required runtime DLLs.`;
6243
6135
  }
6244
- let width = 0;
6245
- let height = 0;
6246
- let seenIdat = false;
6247
- let colorSpaceFromCicp = null;
6248
- let pos = 8;
6249
- while (pos + 12 <= buf.length) {
6250
- const chunkLen = buf.readUInt32BE(pos);
6251
- const chunkType = buf.toString("ascii", pos + 4, pos + 8);
6252
- if (pos + 12 + chunkLen > buf.length) return null;
6253
- const chunkData = buf.subarray(pos + 8, pos + 8 + chunkLen);
6254
- const chunkCrc = buf.readUInt32BE(pos + 8 + chunkLen);
6255
- if (chunkCrc32(chunkType, chunkData) !== chunkCrc) return null;
6256
- if (chunkType === "IHDR" && chunkLen >= 13 && width === 0 && height === 0) {
6257
- width = buf.readUInt32BE(pos + 8);
6258
- height = buf.readUInt32BE(pos + 12);
6259
- }
6260
- if (chunkType === "IDAT") {
6261
- seenIdat = true;
6262
- }
6263
- if (chunkType === "cICP" && chunkLen === 4 && !seenIdat) {
6264
- const primariesCode = chunkData[0] ?? 0;
6265
- const transferCode = chunkData[1] ?? 0;
6266
- const matrixCode = chunkData[2] ?? 0;
6267
- colorSpaceFromCicp = {
6268
- colorPrimaries: primariesCode === 9 ? "bt2020" : primariesCode === 1 ? "bt709" : `unknown-${primariesCode}`,
6269
- colorTransfer: transferCode === 16 ? "smpte2084" : transferCode === 18 ? "arib-std-b67" : transferCode === 1 ? "bt709" : `unknown-${transferCode}`,
6270
- colorSpace: matrixCode === 9 ? "bt2020nc" : matrixCode === 0 ? "gbr" : `unknown-${matrixCode}`
6271
- };
6272
- }
6273
- if (width > 0 && height > 0 && colorSpaceFromCicp !== null) break;
6274
- if (chunkType === "IEND") break;
6275
- pos += 12 + chunkLen;
6136
+ if (exitCode === 3221225595 || exitCode === -1073741701) {
6137
+ return "[FFmpeg] Windows could not start ffmpeg.exe (STATUS_INVALID_IMAGE_FORMAT). The binary may be corrupted or the wrong architecture. Reinstall a 64-bit Windows FFmpeg build.";
6276
6138
  }
6277
- return width > 0 && height > 0 ? { width, height, colorSpace: colorSpaceFromCicp } : null;
6278
- }
6279
- function extractStillImageMetadata(filePath) {
6280
- try {
6281
- return extractPngMetadataFromBuffer(readFileSync2(filePath));
6282
- } catch {
6283
- return null;
6139
+ if (exitCode === 3221225794 || exitCode === -1073741502) {
6140
+ return "[FFmpeg] Windows failed while initializing ffmpeg.exe. The binary may be corrupted, blocked, or missing runtime DLLs. Reinstall a 64-bit Windows FFmpeg build.";
6284
6141
  }
6142
+ return void 0;
6285
6143
  }
6286
- function readTagCI(tags, name) {
6287
- if (!tags) return "";
6288
- const target = name.toLowerCase();
6289
- for (const [key, value] of Object.entries(tags)) {
6290
- if (key.toLowerCase() === target && typeof value === "string") return value;
6144
+ function formatFfmpegError(exitCode, stderr, tailLines = DEFAULT_STDERR_TAIL_LINES) {
6145
+ const tail2 = (stderr ?? "").split(/\r?\n/).filter((line) => line.length > 0).slice(-tailLines).join("\n");
6146
+ if (exitCode === null) {
6147
+ return tail2 ? `[FFmpeg] ${tail2}` : "[FFmpeg] process error";
6291
6148
  }
6292
- return "";
6149
+ const windowsMessage = formatWindowsFfmpegExit(exitCode);
6150
+ if (windowsMessage) {
6151
+ return tail2 ? `${windowsMessage}
6152
+ ffmpeg stderr (tail):
6153
+ ${tail2}` : windowsMessage;
6154
+ }
6155
+ return tail2 ? `FFmpeg exited with code ${exitCode}
6156
+ ffmpeg stderr (tail):
6157
+ ${tail2}` : `FFmpeg exited with code ${exitCode}`;
6293
6158
  }
6294
- function parseFrameRate(frameRateStr) {
6295
- if (!frameRateStr) return 0;
6296
- const parts = frameRateStr.split("/");
6297
- if (parts.length > 2) return 0;
6298
- const strict = (part) => part === void 0 || part.trim() === "" ? NaN : Number(part.trim());
6299
- const raw = parts.length === 2 ? (() => {
6300
- const num = strict(parts[0]);
6301
- const den = strict(parts[1]);
6302
- if (!Number.isFinite(num) || !Number.isFinite(den) || den === 0) return NaN;
6303
- return num / den;
6304
- })() : strict(frameRateStr);
6305
- if (!Number.isFinite(raw) || raw <= 0) return 0;
6306
- const rounded = Math.round(raw * 100) / 100;
6307
- if (!Number.isFinite(rounded)) return 0;
6308
- return rounded > 0 ? rounded : 0.01;
6159
+ function describeFfmpegFailure(result, timeoutMs) {
6160
+ const error = formatFfmpegError(result.exitCode, result.stderr);
6161
+ if (result.terminationReason === "inactivity") {
6162
+ return `FFmpeg timed out after ${timeoutMs} ms without progress (ffmpegProcessTimeout, FFMPEG_PROCESS_TIMEOUT_MS). ${error}`;
6163
+ }
6164
+ if (result.exitCode !== null) return error;
6165
+ const signalOrRequestedStop = result.terminationReason === "exit" ? result.signal : result.terminationReason;
6166
+ return signalOrRequestedStop ? `FFmpeg ended without an exit code (${signalOrRequestedStop}). ${error}` : error;
6309
6167
  }
6310
- function displayRotation(stream) {
6311
- const turn = Number(
6312
- stream.side_data_list?.find((data) => data.rotation !== void 0)?.rotation ?? stream.tags?.rotate ?? 0
6313
- );
6314
- return Number.isFinite(turn) && turn % 360 !== 0 ? { rotation: turn } : {};
6168
+ function spawnFfmpeg(args) {
6169
+ const ffmpeg = spawn2(getFfmpegBinary(), args, { windowsHide: true });
6170
+ trackChildProcess(ffmpeg);
6171
+ return ffmpeg;
6315
6172
  }
6316
- function displaySize(metadata) {
6317
- const width = Math.round(metadata.width * (metadata.sampleAspectRatio ?? 1));
6318
- return Math.abs(metadata.rotation ?? 0) % 180 === 90 ? { width: metadata.height, height: width } : { width, height: metadata.height };
6173
+ function succeeded(outcome) {
6174
+ return outcome.reason === "exit" && outcome.exitCode === 0;
6319
6175
  }
6320
- function parseSampleAspectRatio(value) {
6321
- const [num, den] = (value ?? "").split(":").map(Number);
6322
- if (!num || !den || !Number.isFinite(num) || !Number.isFinite(den)) return void 0;
6323
- const ratio = num / den;
6324
- return Math.abs(ratio - 1) < 1e-3 ? void 0 : ratio;
6176
+ function toResult(outcome, stderr = outcome.stderr) {
6177
+ const result = {
6178
+ success: succeeded(outcome),
6179
+ exitCode: outcome.exitCode,
6180
+ signal: outcome.signal,
6181
+ stderr,
6182
+ durationMs: outcome.durationMs,
6183
+ terminationReason: outcome.reason,
6184
+ error: outcome.error
6185
+ };
6186
+ if (isExternalFfmpegInterruption(result)) {
6187
+ result.failureReason = "external_interruption";
6188
+ }
6189
+ return result;
6325
6190
  }
6326
- async function probeDecodedAlphaPlane(filePath, decoder) {
6327
- let probeDir;
6328
- try {
6329
- probeDir = mkdtempSync2(join5(tmpdir3(), "hf-decoded-alpha-"));
6330
- const framePath = join5(probeDir, "frame.nut");
6331
- const decoded = await runFfmpeg(
6332
- [
6333
- "-v",
6334
- "error",
6191
+ var ABORTED_BEFORE_START = {
6192
+ success: false,
6193
+ exitCode: null,
6194
+ signal: null,
6195
+ stderr: "",
6196
+ durationMs: 0,
6197
+ terminationReason: "abort"
6198
+ };
6199
+ async function runFfmpeg(args, opts) {
6200
+ if (opts?.signal?.aborted) return { ...ABORTED_BEFORE_START };
6201
+ let framesWritten = 0;
6202
+ let secondsWritten = 0;
6203
+ const readStats = ffmpegStatsReader(({ frames = 0, seconds = 0 }) => {
6204
+ if (frames <= framesWritten && seconds <= secondsWritten) return;
6205
+ framesWritten = Math.max(frames, framesWritten);
6206
+ secondsWritten = Math.max(seconds, secondsWritten);
6207
+ managed.markActivity();
6208
+ });
6209
+ const managed = new ManagedChildProcess(spawnFfmpeg(args), {
6210
+ signal: opts?.signal,
6211
+ inactivityTimeoutMs: opts?.timeout ?? DEFAULT_TIMEOUT,
6212
+ onStderr: (chunk) => {
6213
+ readStats(chunk);
6214
+ opts?.onStderr?.(chunk);
6215
+ }
6216
+ });
6217
+ return toResult(await managed.wait());
6218
+ }
6219
+
6220
+ // ../engine/src/utils/ffprobe.ts
6221
+ var FFPROBE_STDERR_MAX_BYTES = 8 * 1024;
6222
+ var FFPROBE_STDOUT_MAX_CHARS = 8e6;
6223
+ var FFPROBE_ERROR_MAX_CHARS = 4 * 1024;
6224
+ function redactFfprobeInput(stderr, filePath) {
6225
+ if (!filePath) return stderr;
6226
+ let redacted = stderr.split(filePath).join("[input]");
6227
+ const inputBasename = basename(filePath);
6228
+ if (inputBasename) redacted = redacted.split(inputBasename).join("[input]");
6229
+ if (!redacted.startsWith("[input]")) {
6230
+ for (let offset = 1; offset < filePath.length; offset += 1) {
6231
+ const suffix = filePath.slice(offset);
6232
+ if (suffix.length < 4 || !redacted.startsWith(suffix)) continue;
6233
+ const boundary = redacted[suffix.length];
6234
+ if (boundary !== void 0 && !/[\s:'")\]}]/.test(boundary)) continue;
6235
+ redacted = `[input]${redacted.slice(suffix.length)}`;
6236
+ break;
6237
+ }
6238
+ }
6239
+ return redacted;
6240
+ }
6241
+ function sanitizeFfprobeDiagnostic(stderr, filePath) {
6242
+ const stderrWithoutInput = redactFfprobeInput(stderr, filePath);
6243
+ const redacted = redactTelemetryString(stderrWithoutInput, FFPROBE_STDERR_MAX_BYTES);
6244
+ if (redacted.length <= FFPROBE_ERROR_MAX_CHARS) return redacted;
6245
+ return `\u2026${redacted.slice(-(FFPROBE_ERROR_MAX_CHARS - 1))}`;
6246
+ }
6247
+ async function runFfprobe(filePath, argsWithoutInput, signal, stdoutOptions) {
6248
+ if (filePath === "-") {
6249
+ throw new Error('[FFmpeg] Refusing to probe "-": stdin is not a supported input path.');
6250
+ }
6251
+ const command = getFfprobeBinary();
6252
+ const args = [
6253
+ "-v",
6254
+ "error",
6255
+ ...urlInputArgs(filePath, { tool: "ffprobe" }),
6256
+ ...argsWithoutInput,
6257
+ "--",
6258
+ filePath
6259
+ ];
6260
+ const proc = spawn3(command, args, {
6261
+ // Nothing is ever written to the child's stdin; leaving it as a pipe is
6262
+ // what lets a stdin-reading invocation block indefinitely.
6263
+ stdio: ["ignore", "pipe", "pipe"],
6264
+ // See runFfmpeg.ts: keeps a console window off the user's desktop on Windows.
6265
+ windowsHide: true
6266
+ });
6267
+ trackChildProcess(proc);
6268
+ const decoder = new StringDecoder2("utf8");
6269
+ let stdout = "";
6270
+ let stdoutTruncated = false;
6271
+ const stdoutMaxChars = stdoutOptions?.maxChars ?? FFPROBE_STDOUT_MAX_CHARS;
6272
+ proc.stdout.on("data", (data) => {
6273
+ if (stdoutTruncated) return;
6274
+ stdout += decoder.write(data);
6275
+ if (stdout.length > stdoutMaxChars) {
6276
+ if (stdoutOptions?.retainTail) {
6277
+ stdout = stdout.slice(-stdoutMaxChars);
6278
+ } else {
6279
+ stdoutTruncated = true;
6280
+ stdout = "";
6281
+ }
6282
+ }
6283
+ });
6284
+ const managed = new ManagedChildProcess(proc, {
6285
+ signal,
6286
+ deadlineAtMs: Date.now() + 3e4,
6287
+ stderrMaxBytes: FFPROBE_STDERR_MAX_BYTES
6288
+ });
6289
+ const outcome = await managed.wait();
6290
+ stdout += decoder.end();
6291
+ if (stdoutTruncated) {
6292
+ throw new Error(
6293
+ `[FFmpeg] ffprobe output exceeded ${stdoutMaxChars} characters; refusing to parse a truncated result.`
6294
+ );
6295
+ }
6296
+ if (outcome.reason === "spawn_error") {
6297
+ if (outcome.error?.code === "ENOENT") {
6298
+ const configured = process.env[FFPROBE_PATH_ENV]?.trim();
6299
+ throw new Error(
6300
+ configured ? `[FFmpeg] ffprobe not found at ${FFPROBE_PATH_ENV}="${configured}". Please install FFmpeg.` : "[FFmpeg] ffprobe not found. Please install FFmpeg."
6301
+ );
6302
+ }
6303
+ throw outcome.error ?? new Error(outcome.stderr);
6304
+ }
6305
+ if (outcome.reason !== "exit" || outcome.exitCode !== 0) {
6306
+ const diagnostic = sanitizeFfprobeDiagnostic(outcome.stderr, filePath);
6307
+ throw new Error(
6308
+ `[FFmpeg] ffprobe ${outcome.reason} with code ${outcome.exitCode}: ${diagnostic}`
6309
+ );
6310
+ }
6311
+ return stdout;
6312
+ }
6313
+ function parseProbeJson(stdout) {
6314
+ try {
6315
+ return JSON.parse(stdout);
6316
+ } catch (e) {
6317
+ throw new Error(
6318
+ `[FFmpeg] Failed to parse ffprobe output: ${e instanceof Error ? e.message : e}`
6319
+ );
6320
+ }
6321
+ }
6322
+ var videoMetadataCache = /* @__PURE__ */ new Map();
6323
+ var finalVideoFrameTimestampCache = /* @__PURE__ */ new Map();
6324
+ var finalVideoFrameTimestampSignalCaches = /* @__PURE__ */ new WeakMap();
6325
+ var audioMetadataCache = /* @__PURE__ */ new Map();
6326
+ var audioMetadataSignalCaches = /* @__PURE__ */ new WeakMap();
6327
+ var mediaProbeOutputCache = /* @__PURE__ */ new Map();
6328
+ var mediaProbeOutputSignalCaches = /* @__PURE__ */ new WeakMap();
6329
+ var MEDIA_PROBE_OUTPUT_CACHE_MAX_ENTRIES = 128;
6330
+ var AUDIO_DURATION_PROBE_MARGIN_SECONDS = 0.05;
6331
+ var AUDIO_DURATION_PROBE_TAIL_SECONDS = 1;
6332
+ var FFPROBE_READ_INTERVAL_EXPLICIT_FAR_END = "+2147483647";
6333
+ var STILL_IMAGE_DEMUXERS = /* @__PURE__ */ new Set([
6334
+ "apng",
6335
+ "bmp_pipe",
6336
+ "dds_pipe",
6337
+ "dpx_pipe",
6338
+ "exr_pipe",
6339
+ "gif",
6340
+ "ico",
6341
+ "image2",
6342
+ "image2pipe",
6343
+ "jpeg_pipe",
6344
+ "jxl_pipe",
6345
+ "png_pipe",
6346
+ "qdraw_pipe",
6347
+ "sgi_pipe",
6348
+ "svg_pipe",
6349
+ "tiff_pipe",
6350
+ "webp_pipe"
6351
+ ]);
6352
+ async function hasAvifFileBrand(filePath) {
6353
+ try {
6354
+ const chunks = [];
6355
+ for await (const chunk of createReadStream(filePath, { start: 0, end: 4095 })) {
6356
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
6357
+ }
6358
+ const bytes = Buffer.concat(chunks);
6359
+ if (bytes.length < 16 || bytes.toString("ascii", 4, 8) !== "ftyp") return false;
6360
+ const boxSize = bytes.readUInt32BE(0);
6361
+ if (boxSize < 16 || boxSize > bytes.length) return false;
6362
+ const avifBrands = /* @__PURE__ */ new Set(["avif", "avis"]);
6363
+ if (avifBrands.has(bytes.toString("ascii", 8, 12))) return true;
6364
+ for (let offset = 16; offset + 4 <= boxSize; offset += 4) {
6365
+ if (avifBrands.has(bytes.toString("ascii", offset, offset + 4))) return true;
6366
+ }
6367
+ return false;
6368
+ } catch {
6369
+ return false;
6370
+ }
6371
+ }
6372
+ async function isStillImageVisual(output, filePath) {
6373
+ const formatNames = (output.format.format_name ?? "").split(",").map((name) => name.trim().toLowerCase()).filter(Boolean);
6374
+ return formatNames.some((name) => STILL_IMAGE_DEMUXERS.has(name)) || await hasAvifFileBrand(filePath);
6375
+ }
6376
+ function isPngImageProbe(output) {
6377
+ const formatNames = (output.format.format_name ?? "").split(",").map((name) => name.trim().toLowerCase());
6378
+ return formatNames.includes("png_pipe") || output.streams.some(
6379
+ (stream) => stream.codec_type === "video" && stream.codec_name?.toLowerCase() === "png"
6380
+ );
6381
+ }
6382
+ var contentAddressedUrls = /* @__PURE__ */ new Map();
6383
+ var withoutQuery = (url) => url.split(/[?#]/, 1)[0] ?? url;
6384
+ function declareContentAddressedUrl(url, sha256) {
6385
+ contentAddressedUrls.set(withoutQuery(url), sha256);
6386
+ }
6387
+ var probeFactsUrls = /* @__PURE__ */ new Map();
6388
+ function declareProbeFactsUrl(url, factsUrl) {
6389
+ probeFactsUrls.set(withoutQuery(url), factsUrl);
6390
+ }
6391
+ function mediaFileIdentity(filePath) {
6392
+ if (/^https?:\/\//i.test(filePath)) {
6393
+ const sha256 = contentAddressedUrls.get(withoutQuery(filePath));
6394
+ return sha256 ? `sha256:${sha256}` : null;
6395
+ }
6396
+ try {
6397
+ const stat = statSync(filePath, { bigint: true });
6398
+ return [stat.dev, stat.ino, stat.size, stat.mtimeNs, stat.ctimeNs].join(":");
6399
+ } catch {
6400
+ return null;
6401
+ }
6402
+ }
6403
+ function readMetadataCache(cache, key, identity) {
6404
+ const cached = cache.get(key);
6405
+ return cached?.identity === identity ? cached.promise : void 0;
6406
+ }
6407
+ function writeMetadataCache(cache, key, identity, promise) {
6408
+ const entry = { identity, promise };
6409
+ cache.set(key, entry);
6410
+ void promise.then(
6411
+ () => {
6412
+ if (identity === null && cache.get(key) === entry) cache.delete(key);
6413
+ },
6414
+ () => {
6415
+ if (cache.get(key) === entry) cache.delete(key);
6416
+ }
6417
+ );
6418
+ }
6419
+ var PROBE_FACTS_VERSION = "v2";
6420
+ var PROBE_JSON_ARGS = ["-print_format", "json", "-show_format", "-show_streams"];
6421
+ var storedFacts = /* @__PURE__ */ new Map();
6422
+ function readStoredFacts(filePath) {
6423
+ if (!/^https?:\/\//i.test(filePath)) return void 0;
6424
+ const factsUrl = probeFactsUrls.get(withoutQuery(filePath));
6425
+ if (!factsUrl) return void 0;
6426
+ let facts = storedFacts.get(factsUrl);
6427
+ if (!facts) {
6428
+ facts = (async () => {
6429
+ try {
6430
+ const response = await fetch(factsUrl, { signal: AbortSignal.timeout(1e4) });
6431
+ if (!response.ok) return null;
6432
+ const parsed = JSON.parse(await response.text());
6433
+ return Array.isArray(parsed.ffprobe?.streams) ? parsed : null;
6434
+ } catch {
6435
+ return null;
6436
+ }
6437
+ })();
6438
+ storedFacts.set(factsUrl, facts);
6439
+ }
6440
+ return facts;
6441
+ }
6442
+ function readProbeJson(filePath, signal) {
6443
+ const pending = readStoredFacts(filePath);
6444
+ if (!pending) return runFfprobe(filePath, PROBE_JSON_ARGS, signal);
6445
+ return pending.then(
6446
+ (stored) => stored ? JSON.stringify(stored.ffprobe) : runFfprobe(filePath, PROBE_JSON_ARGS, signal)
6447
+ );
6448
+ }
6449
+ var runtimeFfprobeMajor;
6450
+ function ffprobeMajor() {
6451
+ runtimeFfprobeMajor ??= new Promise((resolve3) => {
6452
+ let out = "";
6453
+ const binary = getFfprobeBinary();
6454
+ const proc = spawn3(binary, ["-version"], {
6455
+ stdio: ["ignore", "pipe", "ignore"],
6456
+ windowsHide: true
6457
+ });
6458
+ proc.stdout.on("data", (chunk) => out += String(chunk));
6459
+ proc.on("error", () => resolve3(void 0));
6460
+ proc.on("close", () => resolve3(Number(/version n?(\d+)/.exec(out)?.[1]) || void 0));
6461
+ });
6462
+ return runtimeFfprobeMajor;
6463
+ }
6464
+ async function buildProbeFactsText(filePath, signal) {
6465
+ const facts = {
6466
+ ffprobe: parseProbeJson(await runFfprobe(filePath, PROBE_JSON_ARGS, signal)),
6467
+ ffprobeMajor: await ffprobeMajor()
6468
+ };
6469
+ try {
6470
+ const metadata = await extractMediaMetadata(filePath);
6471
+ const window2 = resolveStreamWindow(filePath, {
6472
+ videoStreamStartSeconds: metadata.videoStreamStartSeconds,
6473
+ videoStreamDurationSeconds: resolvePlayableVideoDuration(metadata) - (metadata.videoStreamLeadSeconds ?? 0)
6474
+ });
6475
+ if (window2.videoStreamDurationSeconds > 0) {
6476
+ facts.finalFrame = {
6477
+ streamStart: window2.videoStreamStartSeconds,
6478
+ streamDuration: window2.videoStreamDurationSeconds,
6479
+ seconds: await extractFinalVideoFrameTimestamp(filePath, window2, signal),
6480
+ lastPacketSeconds: await extractFinalPacketDuration(filePath, window2, signal)
6481
+ };
6482
+ }
6483
+ } catch {
6484
+ if (signal?.aborted) throw signal.reason;
6485
+ }
6486
+ return JSON.stringify(facts);
6487
+ }
6488
+ function videoStartOnMediaTimeline(metadata) {
6489
+ return (metadata.videoStreamLeadSeconds ?? 0) + (metadata.mediaTimeOffsetSeconds ?? 0);
6490
+ }
6491
+ function formatFfmpegSeconds(seconds) {
6492
+ const text = String(seconds);
6493
+ return text.includes("e") ? String(+seconds.toFixed(6)) : text;
6494
+ }
6495
+ function readIntervalSpec(startSeconds, end) {
6496
+ const to = typeof end === "number" ? formatFfmpegSeconds(end) : end;
6497
+ return `${formatFfmpegSeconds(startSeconds)}%${to}`;
6498
+ }
6499
+ function ffmpegSeekSeconds(metadata, mediaTime) {
6500
+ return mediaTime - (metadata.mediaTimeOffsetSeconds ?? 0);
6501
+ }
6502
+ function resolvePlayableVideoDuration(metadata) {
6503
+ return Number.isFinite(metadata.videoStreamDurationSeconds) && metadata.videoStreamDurationSeconds > 0 ? (metadata.videoStreamLeadSeconds ?? 0) + metadata.videoStreamDurationSeconds : metadata.durationSeconds;
6504
+ }
6505
+ async function probeMediaOutput(filePath, signal) {
6506
+ let cache = mediaProbeOutputCache;
6507
+ if (signal) {
6508
+ cache = mediaProbeOutputSignalCaches.get(signal) ?? /* @__PURE__ */ new Map();
6509
+ mediaProbeOutputSignalCaches.set(signal, cache);
6510
+ }
6511
+ const identity = mediaFileIdentity(filePath);
6512
+ const cached = cache.get(filePath);
6513
+ if (identity !== null && cached?.identity === identity) {
6514
+ if (!signal) {
6515
+ cache.delete(filePath);
6516
+ cache.set(filePath, cached);
6517
+ }
6518
+ return cached.promise;
6519
+ }
6520
+ const promise = readProbeJson(filePath, signal).then(
6521
+ (json) => refuseTextArt(parseProbeJson(json))
6522
+ );
6523
+ if (identity !== null) {
6524
+ cache.set(filePath, { identity, promise });
6525
+ if (!signal && cache.size > MEDIA_PROBE_OUTPUT_CACHE_MAX_ENTRIES) {
6526
+ const oldestPath = cache.keys().next().value;
6527
+ if (oldestPath !== void 0) cache.delete(oldestPath);
6528
+ }
6529
+ }
6530
+ promise.catch(() => {
6531
+ if (cache.get(filePath)?.promise === promise) {
6532
+ cache.delete(filePath);
6533
+ }
6534
+ });
6535
+ return promise;
6536
+ }
6537
+ var StructurallyIncompletePngError = class extends Error {
6538
+ };
6539
+ var TEXT_ART_CODECS = /* @__PURE__ */ new Set(["ansi", "bintext", "xbin", "idf"]);
6540
+ function refuseTextArt(output) {
6541
+ const formats = (output.format?.format_name ?? "").toLowerCase().split(",");
6542
+ const drawsText = (output.streams ?? []).some(
6543
+ (stream) => stream.codec_type === "video" && TEXT_ART_CODECS.has(stream.codec_name?.toLowerCase() ?? "")
6544
+ );
6545
+ if (formats.includes("tty") || drawsText) throw new TextArtMediaError();
6546
+ return output;
6547
+ }
6548
+ async function readFileRange(filePath, start, length, signal) {
6549
+ const chunks = [];
6550
+ for await (const chunk of createReadStream(filePath, {
6551
+ start,
6552
+ end: start + length - 1,
6553
+ highWaterMark: length,
6554
+ signal
6555
+ })) {
6556
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
6557
+ }
6558
+ return Buffer.concat(chunks);
6559
+ }
6560
+ async function hasCompletePngStructure(filePath, signal) {
6561
+ try {
6562
+ signal?.throwIfAborted();
6563
+ const fileSize = statSync(filePath).size;
6564
+ const signature = await readFileRange(filePath, 0, 8, signal);
6565
+ signal?.throwIfAborted();
6566
+ if (signature.length !== 8 || !signature.equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]))) {
6567
+ return false;
6568
+ }
6569
+ let seenHeader = false;
6570
+ let seenImageData = false;
6571
+ let offset = 8;
6572
+ while (offset + 12 <= fileSize) {
6573
+ signal?.throwIfAborted();
6574
+ const chunkHeader = await readFileRange(filePath, offset, 8, signal);
6575
+ signal?.throwIfAborted();
6576
+ if (chunkHeader.length !== 8) return false;
6577
+ const chunkLength = chunkHeader.readUInt32BE(0);
6578
+ const chunkEnd = offset + 12 + chunkLength;
6579
+ if (chunkEnd > fileSize) return false;
6580
+ const chunkType = chunkHeader.toString("ascii", 4, 8);
6581
+ if (chunkType === "IHDR") seenHeader = chunkLength === 13 && offset === 8;
6582
+ if (chunkType === "IDAT") seenImageData = true;
6583
+ if (chunkType === "IEND") return seenHeader && seenImageData && chunkLength === 0;
6584
+ offset = chunkEnd;
6585
+ }
6586
+ return false;
6587
+ } catch (error) {
6588
+ if (signal?.aborted) throw signal.reason ?? error;
6589
+ return false;
6590
+ }
6591
+ }
6592
+ async function probeMediaProfile(filePath, options) {
6593
+ try {
6594
+ const output = await probeMediaOutput(filePath, options?.signal);
6595
+ options?.signal?.throwIfAborted();
6596
+ const videoStreams = output.streams.filter((stream) => stream.codec_type === "video");
6597
+ const hasMovingVideoStream = videoStreams.some(
6598
+ (stream) => stream.disposition?.attached_pic !== 1
6599
+ );
6600
+ const isStillImage = videoStreams.length > 0 && await isStillImageVisual(output, filePath);
6601
+ options?.signal?.throwIfAborted();
6602
+ if (isStillImage && isPngImageProbe(output) && !await hasCompletePngStructure(filePath, options?.signal)) {
6603
+ throw new StructurallyIncompletePngError("[FFmpeg] PNG input is structurally incomplete");
6604
+ }
6605
+ return {
6606
+ hasVideoStream: videoStreams.length > 0,
6607
+ hasAudioStream: decodableAudioStream(output.streams) !== null,
6608
+ visualKind: isStillImage ? "still" : hasMovingVideoStream ? "moving" : "none"
6609
+ };
6610
+ } catch (error) {
6611
+ if (options?.signal?.aborted) throw options.signal.reason ?? error;
6612
+ if (error instanceof StructurallyIncompletePngError) throw error;
6613
+ const stillImage = extractStillImageMetadata(filePath);
6614
+ if (stillImage && await hasCompletePngStructure(filePath, options?.signal)) {
6615
+ return { hasVideoStream: true, hasAudioStream: false, visualKind: "still" };
6616
+ }
6617
+ throw error;
6618
+ }
6619
+ }
6620
+ function extractPngMetadataFromBuffer(buf) {
6621
+ if (buf.length < 8 || buf[0] !== 137 || buf[1] !== 80 || buf[2] !== 78 || buf[3] !== 71 || buf[4] !== 13 || buf[5] !== 10 || buf[6] !== 26 || buf[7] !== 10) {
6622
+ return null;
6623
+ }
6624
+ let width = 0;
6625
+ let height = 0;
6626
+ let seenIdat = false;
6627
+ let colorSpaceFromCicp = null;
6628
+ let pos = 8;
6629
+ while (pos + 12 <= buf.length) {
6630
+ const chunkLen = buf.readUInt32BE(pos);
6631
+ const chunkType = buf.toString("ascii", pos + 4, pos + 8);
6632
+ if (pos + 12 + chunkLen > buf.length) return null;
6633
+ const chunkData = buf.subarray(pos + 8, pos + 8 + chunkLen);
6634
+ const chunkCrc = buf.readUInt32BE(pos + 8 + chunkLen);
6635
+ if (chunkCrc32(chunkType, chunkData) !== chunkCrc) return null;
6636
+ if (chunkType === "IHDR" && chunkLen >= 13 && width === 0 && height === 0) {
6637
+ width = buf.readUInt32BE(pos + 8);
6638
+ height = buf.readUInt32BE(pos + 12);
6639
+ }
6640
+ if (chunkType === "IDAT") {
6641
+ seenIdat = true;
6642
+ }
6643
+ if (chunkType === "cICP" && chunkLen === 4 && !seenIdat) {
6644
+ const primariesCode = chunkData[0] ?? 0;
6645
+ const transferCode = chunkData[1] ?? 0;
6646
+ const matrixCode = chunkData[2] ?? 0;
6647
+ colorSpaceFromCicp = {
6648
+ colorPrimaries: primariesCode === 9 ? "bt2020" : primariesCode === 1 ? "bt709" : `unknown-${primariesCode}`,
6649
+ colorTransfer: transferCode === 16 ? "smpte2084" : transferCode === 18 ? "arib-std-b67" : transferCode === 1 ? "bt709" : `unknown-${transferCode}`,
6650
+ colorSpace: matrixCode === 9 ? "bt2020nc" : matrixCode === 0 ? "gbr" : `unknown-${matrixCode}`
6651
+ };
6652
+ }
6653
+ if (width > 0 && height > 0 && colorSpaceFromCicp !== null) break;
6654
+ if (chunkType === "IEND") break;
6655
+ pos += 12 + chunkLen;
6656
+ }
6657
+ return width > 0 && height > 0 ? { width, height, colorSpace: colorSpaceFromCicp } : null;
6658
+ }
6659
+ function extractStillImageMetadata(filePath) {
6660
+ try {
6661
+ return extractPngMetadataFromBuffer(readFileSync2(filePath));
6662
+ } catch {
6663
+ return null;
6664
+ }
6665
+ }
6666
+ function readTagCI(tags, name) {
6667
+ if (!tags) return "";
6668
+ const target = name.toLowerCase();
6669
+ for (const [key, value] of Object.entries(tags)) {
6670
+ if (key.toLowerCase() === target && typeof value === "string") return value;
6671
+ }
6672
+ return "";
6673
+ }
6674
+ function parseFrameRate(frameRateStr) {
6675
+ if (!frameRateStr) return 0;
6676
+ const parts = frameRateStr.split("/");
6677
+ if (parts.length > 2) return 0;
6678
+ const strict = (part) => part === void 0 || part.trim() === "" ? NaN : Number(part.trim());
6679
+ const raw = parts.length === 2 ? (() => {
6680
+ const num = strict(parts[0]);
6681
+ const den = strict(parts[1]);
6682
+ if (!Number.isFinite(num) || !Number.isFinite(den) || den === 0) return NaN;
6683
+ return num / den;
6684
+ })() : strict(frameRateStr);
6685
+ if (!Number.isFinite(raw) || raw <= 0) return 0;
6686
+ const rounded = Math.round(raw * 100) / 100;
6687
+ if (!Number.isFinite(rounded)) return 0;
6688
+ return rounded > 0 ? rounded : 0.01;
6689
+ }
6690
+ function displayRotation(stream) {
6691
+ const turn = Number(
6692
+ stream.side_data_list?.find((data) => data.rotation !== void 0)?.rotation ?? stream.tags?.rotate ?? 0
6693
+ );
6694
+ return Number.isFinite(turn) && turn % 360 !== 0 ? { rotation: turn } : {};
6695
+ }
6696
+ function displaySize(metadata) {
6697
+ const width = Math.round(metadata.width * (metadata.sampleAspectRatio ?? 1));
6698
+ return Math.abs(metadata.rotation ?? 0) % 180 === 90 ? { width: metadata.height, height: width } : { width, height: metadata.height };
6699
+ }
6700
+ function parseSampleAspectRatio(value) {
6701
+ const [num, den] = (value ?? "").split(":").map(Number);
6702
+ if (!num || !den || !Number.isFinite(num) || !Number.isFinite(den)) return void 0;
6703
+ const ratio = num / den;
6704
+ return Math.abs(ratio - 1) < 1e-3 ? void 0 : ratio;
6705
+ }
6706
+ async function probeDecodedAlphaPlane(filePath, decoder) {
6707
+ let probeDir;
6708
+ try {
6709
+ probeDir = mkdtempSync2(join5(tmpdir3(), "hf-decoded-alpha-"));
6710
+ const framePath = join5(probeDir, "frame.nut");
6711
+ const decoded = await runFfmpeg(
6712
+ [
6713
+ "-v",
6714
+ "error",
6335
6715
  ...urlInputArgs(filePath),
6336
6716
  "-c:v",
6337
6717
  decoder,
@@ -6811,7 +7191,7 @@ function resolveOwnVersionFrom(startDir) {
6811
7191
  reportUnresolved(`found ${pkg.name} at ${candidate} but it declares no version`);
6812
7192
  return UNRESOLVED_VERSION;
6813
7193
  }
6814
- const parent = dirname2(dir);
7194
+ const parent = dirname3(dir);
6815
7195
  if (parent === dir) break;
6816
7196
  dir = parent;
6817
7197
  }
@@ -6839,7 +7219,7 @@ function reportUnresolved(reason) {
6839
7219
  }
6840
7220
  function readEngineVersion() {
6841
7221
  try {
6842
- return resolveOwnVersionFrom(dirname2(fileURLToPath2(import.meta.url)));
7222
+ return resolveOwnVersionFrom(dirname3(fileURLToPath2(import.meta.url)));
6843
7223
  } catch {
6844
7224
  reportUnresolved("import.meta.url is not a file URL");
6845
7225
  return UNRESOLVED_VERSION;
@@ -7683,7 +8063,9 @@ async function initDrawElementOrTransparentBackground(session, page, logInitPhas
7683
8063
  session.deGateReason = reason;
7684
8064
  session.deFallbackTrigger = trigger;
7685
8065
  console.error(
7686
- `[engine] fast capture falls back to ${session.launchCaptureMode} capture: ${message}`
8066
+ terminalText(
8067
+ `[engine] fast capture falls back to ${session.launchCaptureMode} capture: ${message}`
8068
+ )
7687
8069
  );
7688
8070
  await routeToFallback();
7689
8071
  };
@@ -7704,7 +8086,11 @@ async function initDrawElementOrTransparentBackground(session, page, logInitPhas
7704
8086
  }
7705
8087
  if (!forceDE && process.env.HF_FAST_CAPTURE_INTERVAL_SS !== "false") {
7706
8088
  const fps = fpsToNumber(session.options.fps);
7707
- const { frames: atRisk, totalFrames } = await computeTimelineAtRiskFrames(page, fps);
8089
+ const { frames: atRisk, totalFrames } = await computeTimelineAtRiskFrames(
8090
+ page,
8091
+ fps,
8092
+ session.options.compositionDurationSeconds
8093
+ );
7708
8094
  const atRiskFraction = atRisk.size / totalFrames;
7709
8095
  const fractionFloor = Number(process.env.HF_FAST_CAPTURE_INTERVAL_FRACTION ?? "0");
7710
8096
  logInitPhase(
@@ -7754,7 +8140,9 @@ async function initDrawElementOrTransparentBackground(session, page, logInitPhas
7754
8140
  session.deGateReason = "3d_init_failed";
7755
8141
  session.deFallbackTrigger = "3d_init_failed";
7756
8142
  console.error(
7757
- `[engine] fast capture falls back to ${session.launchCaptureMode} capture: 3D projection init failed (${threeD.reason ?? "unknown"})`
8143
+ terminalText(
8144
+ `[engine] fast capture falls back to ${session.launchCaptureMode} capture: 3D projection init failed (${threeD.reason ?? "unknown"})`
8145
+ )
7758
8146
  );
7759
8147
  await routeToFallback();
7760
8148
  return;
@@ -7815,7 +8203,9 @@ async function cssEffectRiskFrames(session, totalFrames) {
7815
8203
  return live && withFramesAfterCallback(live, scan.callbackFrom, fps, totalFrames);
7816
8204
  } catch (error) {
7817
8205
  console.error(
7818
- `[engine] fast capture: effect scan failed (${error instanceof Error ? error.message : String(error)})`
8206
+ terminalText(
8207
+ `[engine] fast capture: effect scan failed (${error instanceof Error ? error.message : String(error)})`
8208
+ )
7819
8209
  );
7820
8210
  return null;
7821
8211
  } finally {
@@ -8386,7 +8776,9 @@ async function pollSubCompositionTimelines(page, timeoutMs, {
8386
8776
  if (failed.length > 0 && sinceFailure >= graceMs) {
8387
8777
  scriptFailureBail = true;
8388
8778
  console.warn(
8389
- `[FrameCapture] Sub-composition timeline wait cut short after ${now - start}ms: script(s) failed (${failed.join(", ")}), so the timeline registration they carry can never arrive. Fix the script.`
8779
+ terminalText(
8780
+ `[FrameCapture] Sub-composition timeline wait cut short after ${now - start}ms: script(s) failed (${failed.join(", ")}), so the timeline registration they carry can never arrive. Fix the script.`
8781
+ )
8390
8782
  );
8391
8783
  break;
8392
8784
  }
@@ -8407,10 +8799,14 @@ async function pollSubCompositionTimelines(page, timeoutMs, {
8407
8799
  onPending?.(pendingIds);
8408
8800
  const missing = pendingIds.join(", ");
8409
8801
  if (scriptFailureBail) {
8410
- console.warn(`[FrameCapture] Composition(s) still waiting on the failed script: ${missing}.`);
8802
+ console.warn(
8803
+ `[FrameCapture] Composition(s) still waiting on the failed script: ${terminalText(missing)}.`
8804
+ );
8411
8805
  } else {
8412
8806
  console.warn(
8413
- `[FrameCapture] Sub-composition timelines not registered after ${timeoutMs}ms: ${missing}. Compositions that load data asynchronously (e.g. fetch) must register window.__timelines[id] after setup completes. Compositions intentionally driven without GSAP timelines (CSS animations / rAF) can mark the host with data-no-timeline to skip this wait.`
8807
+ terminalText(
8808
+ `[FrameCapture] Sub-composition timelines not registered after ${timeoutMs}ms: ${missing}. Compositions that load data asynchronously (e.g. fetch) must register window.__timelines[id] after setup completes. Compositions intentionally driven without GSAP timelines (CSS animations / rAF) can mark the host with data-no-timeline to skip this wait.`
8809
+ )
8414
8810
  );
8415
8811
  }
8416
8812
  return scriptFailureBail ? "script_failure" : "timeout";
@@ -8529,7 +8925,10 @@ function recordCaptureWarnings(session, warnings) {
8529
8925
  continue;
8530
8926
  }
8531
8927
  session.warnings.push(warning);
8532
- console.warn(`[FrameCapture:${warning.code}] ${warning.message}`, warning.details ?? {});
8928
+ console.warn(
8929
+ `[FrameCapture:${warning.code}] ${terminalText(warning.message)}`,
8930
+ warning.details ?? {}
8931
+ );
8533
8932
  }
8534
8933
  }
8535
8934
  function recordReadiness(session, warnings) {
@@ -8895,7 +9294,7 @@ async function initializeSession(session) {
8895
9294
  const locationUrl = msg.location()?.url ?? "";
8896
9295
  const diagnostic = formatConsoleDiagnostic(type, text, locationUrl);
8897
9296
  if (!diagnostic.suppressHostLog && !quietRuntimeDetail(text) && !loggedEarlierInRender(session, text)) {
8898
- console.error(diagnostic.text);
9297
+ console.error(terminalText(diagnostic.text));
8899
9298
  }
8900
9299
  appendBrowserDiagnostic(session, diagnostic.text);
8901
9300
  const scriptFailure = classifyConsoleScriptFailure(type, text);
@@ -8906,7 +9305,7 @@ async function initializeSession(session) {
8906
9305
  page.on("pageerror", (err) => {
8907
9306
  const message = err instanceof Error ? err.message : String(err);
8908
9307
  const text = `[Browser:PAGEERROR] ${message}`;
8909
- if (!isPlayPauseAbort(message)) console.error(text);
9308
+ if (!isPlayPauseAbort(message)) console.error(terminalText(text));
8910
9309
  appendBrowserDiagnostic(session, text);
8911
9310
  });
8912
9311
  page.on("requestfailed", (request) => recordFailedRequest(session, request));
@@ -9011,7 +9410,9 @@ async function initializeSession(session) {
9011
9410
  page,
9012
9411
  pageReadyTimeout,
9013
9412
  (failedImages) => console.warn(
9014
- `[FrameCapture] Some image elements did not load within ${pageReadyTimeout}ms: ${failedImages}. Continuing render. Affected images may appear blank/missing in early frames.`
9413
+ terminalText(
9414
+ `[FrameCapture] Some image elements did not load within ${pageReadyTimeout}ms: ${failedImages}. Continuing render. Affected images may appear blank/missing in early frames.`
9415
+ )
9015
9416
  )
9016
9417
  ),
9017
9418
  page.evaluate(`document.fonts?.ready`),
@@ -9024,7 +9425,9 @@ async function initializeSession(session) {
9024
9425
  return Array.from(document.querySelectorAll("video")).filter((v) => !skip.has(v.id)).filter((v) => !v.closest("[data-hidden]")).filter((v) => v.readyState < 2 && !v.error).map((v) => v.src || v.getAttribute("src") || "(no src)").join(", ");
9025
9426
  }, skipVideoIds);
9026
9427
  console.warn(
9027
- `[FrameCapture] Some video elements did not decode within ${pageReadyTimeout}ms: ${failedVideos}. Continuing render. Affected videos will appear as blank/black frames.`
9428
+ terminalText(
9429
+ `[FrameCapture] Some video elements did not decode within ${pageReadyTimeout}ms: ${failedVideos}. Continuing render. Affected videos will appear as blank/black frames.`
9430
+ )
9028
9431
  );
9029
9432
  }
9030
9433
  recordReadiness(
@@ -9108,7 +9511,9 @@ async function initializeSession(session) {
9108
9511
  page,
9109
9512
  pageReadyTimeout,
9110
9513
  (failedImages) => console.warn(
9111
- `[FrameCapture] Some image elements did not load within ${pageReadyTimeout}ms: ${failedImages}. Continuing render. Affected images may appear blank/missing in early frames.`
9514
+ terminalText(
9515
+ `[FrameCapture] Some image elements did not load within ${pageReadyTimeout}ms: ${failedImages}. Continuing render. Affected images may appear blank/missing in early frames.`
9516
+ )
9112
9517
  )
9113
9518
  ),
9114
9519
  page.evaluate(`document.fonts?.ready`),
@@ -9121,7 +9526,9 @@ async function initializeSession(session) {
9121
9526
  return Array.from(document.querySelectorAll("video")).filter((v) => !skip.has(v.id)).filter((v) => !v.closest("[data-hidden]")).filter((v) => v.readyState < 2 && !v.error).map((v) => v.src || v.getAttribute("src") || "(no src)").join(", ");
9122
9527
  }, bfSkipVideoIds);
9123
9528
  console.warn(
9124
- `[FrameCapture] Some video elements did not decode within ${pageReadyTimeout}ms: ${failedVideos}. Continuing render. Affected videos will appear as blank/black frames.`
9529
+ terminalText(
9530
+ `[FrameCapture] Some video elements did not decode within ${pageReadyTimeout}ms: ${failedVideos}. Continuing render. Affected videos will appear as blank/black frames.`
9531
+ )
9125
9532
  );
9126
9533
  }
9127
9534
  recordReadiness(
@@ -9281,6 +9688,28 @@ var MAX_STATIC_DEDUP_ANALYSIS_FRAMES = 1e6;
9281
9688
  function isStaticDedupFrameAnalysisSafe(totalFrames) {
9282
9689
  return Number.isFinite(totalFrames) && Number.isSafeInteger(totalFrames) && totalFrames > 0 && totalFrames <= MAX_STATIC_DEDUP_ANALYSIS_FRAMES;
9283
9690
  }
9691
+ var MAX_TIMELINE_FRAME_INTERVALS = 1e5;
9692
+ function tweenFrameRange(start, end, fps, margin, maxFrame) {
9693
+ const lo = Math.max(0, Math.floor(start * fps) - margin);
9694
+ const hi = Math.min(maxFrame, Math.ceil(end * fps) + margin);
9695
+ if (Number.isNaN(lo) || Number.isNaN(hi) || lo > hi) return null;
9696
+ return [lo, hi];
9697
+ }
9698
+ function mergeFrameRanges(ranges) {
9699
+ const sorted = [...ranges].sort((a, b) => a[0] - b[0]);
9700
+ const merged = [];
9701
+ for (const [lo, hi] of sorted) {
9702
+ const last = merged[merged.length - 1];
9703
+ if (last && lo <= last[1] + 1) last[1] = Math.max(last[1], hi);
9704
+ else merged.push([lo, hi]);
9705
+ }
9706
+ return merged;
9707
+ }
9708
+ function addFrameRanges(target, ranges) {
9709
+ for (const [lo, hi] of mergeFrameRanges(ranges)) {
9710
+ for (let f = lo; f <= hi; f++) target.add(f);
9711
+ }
9712
+ }
9284
9713
  async function computeStaticFrameSet(page, fps, ignoredVideoIds = []) {
9285
9714
  const result = await page.evaluate(
9286
9715
  (spatialProps, ignored) => {
@@ -9389,16 +9818,31 @@ async function computeStaticFrameSet(page, fps, ignoredVideoIds = []) {
9389
9818
  reason: `static-dedup frame analysis limit (${MAX_STATIC_DEDUP_ANALYSIS_FRAMES})`
9390
9819
  };
9391
9820
  }
9392
- const animated = /* @__PURE__ */ new Set();
9393
- const spatialFrameSet = /* @__PURE__ */ new Set();
9821
+ if (intervals.length > MAX_TIMELINE_FRAME_INTERVALS) {
9822
+ return {
9823
+ totalFrames,
9824
+ staticFrameSet: /* @__PURE__ */ new Set(),
9825
+ nonSpatialOnlyFrameSet: /* @__PURE__ */ new Set(),
9826
+ hasVideo,
9827
+ hasCanvas,
9828
+ hasNonGsapAnim,
9829
+ tweenCount,
9830
+ eligible: false,
9831
+ reason: `static-dedup tween interval limit (${MAX_TIMELINE_FRAME_INTERVALS})`
9832
+ };
9833
+ }
9834
+ const animatedRanges = [];
9835
+ const spatialRanges = [];
9394
9836
  for (const { start, end, spatial } of intervals) {
9395
- const lo = Math.max(0, Math.floor(start * fps));
9396
- const hi = Math.min(totalFrames - 1, Math.ceil(end * fps));
9397
- for (let f = lo; f <= hi; f++) {
9398
- animated.add(f);
9399
- if (spatial) spatialFrameSet.add(f);
9400
- }
9837
+ const range = tweenFrameRange(start, end, fps, 0, totalFrames - 1);
9838
+ if (!range) continue;
9839
+ animatedRanges.push(range);
9840
+ if (spatial) spatialRanges.push(range);
9401
9841
  }
9842
+ const animated = /* @__PURE__ */ new Set();
9843
+ const spatialFrameSet = /* @__PURE__ */ new Set();
9844
+ addFrameRanges(animated, animatedRanges);
9845
+ addFrameRanges(spatialFrameSet, spatialRanges);
9402
9846
  for (const f of await computeClipBoundaryFrames(page, fps)) animated.add(f);
9403
9847
  const reasons = [];
9404
9848
  if (!(duration > 0)) reasons.push("unknown/zero duration");
@@ -9895,7 +10339,7 @@ async function verifyAndArmStaticDedup(session, stats, fps, samples, logInitPhas
9895
10339
  `static-frame dedup: ${verdict.verifiedFrames.size}/${stats.staticFrameSet.size} predicted frame(s) reusable (outcome=${verdict.outcome}, runs=${verdict.stats.completedRuns}/${verdict.stats.plannedRuns}, screenshots=${verdict.stats.screenshots}, seeks=${verdict.stats.seeks}, elapsedMs=${verdict.stats.elapsedMs})`
9896
10340
  );
9897
10341
  }
9898
- async function computeTimelineAtRiskFrames(page, fps) {
10342
+ async function computeTimelineAtRiskFrames(page, fps, renderDurationSeconds) {
9899
10343
  const result = await page.evaluate(() => {
9900
10344
  const AT_RISK_PROPS = /* @__PURE__ */ new Set([
9901
10345
  "backdropFilter",
@@ -9940,15 +10384,19 @@ async function computeTimelineAtRiskFrames(page, fps) {
9940
10384
  return { intervals: intervals2, duration: duration2 };
9941
10385
  });
9942
10386
  const { intervals, duration } = result;
10387
+ const totalFrames = Math.max(1, Math.ceil(duration * fps));
10388
+ const lastFrame = Math.max(1, Math.ceil((renderDurationSeconds ?? duration) * fps)) - 1;
9943
10389
  const frames = /* @__PURE__ */ new Set();
10390
+ if (intervals.length > MAX_TIMELINE_FRAME_INTERVALS) {
10391
+ addFrameRanges(frames, [[0, lastFrame]]);
10392
+ return { frames, totalFrames };
10393
+ }
10394
+ const ranges = [];
9944
10395
  for (const { start, end } of intervals) {
9945
- const lo = Math.floor(start * fps) - 1;
9946
- const hi = Math.ceil(end * fps) + 1;
9947
- for (let f = Math.max(0, lo); f <= hi; f++) {
9948
- frames.add(f);
9949
- }
10396
+ const range = tweenFrameRange(start, end, fps, 1, lastFrame);
10397
+ if (range) ranges.push(range);
9950
10398
  }
9951
- const totalFrames = Math.max(1, Math.ceil(duration * fps));
10399
+ addFrameRanges(frames, ranges);
9952
10400
  return { frames, totalFrames };
9953
10401
  }
9954
10402
  function isNoCachedPaintRecordError(err) {
@@ -10287,7 +10735,7 @@ async function captureFrameCore(session, frameIndex, time) {
10287
10735
  session.page,
10288
10736
  pageMotionBlurRecorder(session)
10289
10737
  ).catch(() => null);
10290
- if (blur) console.error(blur);
10738
+ if (blur) console.error(terminalText(blur));
10291
10739
  }
10292
10740
  if (session.staticFrames) {
10293
10741
  session.lastFrameBuffer = buffer;
@@ -10476,7 +10924,9 @@ async function captureFramesBatchPipelined(session, frameIndices, times) {
10476
10924
  throw new DrawElementCaptureError(frameIndices[failedAt] ?? failedAt, reason, error);
10477
10925
  } else {
10478
10926
  console.error(
10479
- `[engine] fast capture: batch produce failed at frame ${frameIndices[failedAt] ?? "?"} (${error ?? "?"}); re-capturing ${frameIndices.length - failedAt} frame(s) per-frame`
10927
+ terminalText(
10928
+ `[engine] fast capture: batch produce failed at frame ${frameIndices[failedAt] ?? "?"} (${error ?? "?"}); re-capturing ${frameIndices.length - failedAt} frame(s) per-frame`
10929
+ )
10480
10930
  );
10481
10931
  for (let i = failedAt; i < frameIndices.length; i++) {
10482
10932
  const frameIndex = frameIndices[i];
@@ -10520,7 +10970,7 @@ async function closeCaptureSession(session) {
10520
10970
  void 0,
10521
10971
  pageMotionBlurRecorder(session)
10522
10972
  );
10523
- if (blur) console.error(blur);
10973
+ if (blur) console.error(terminalText(blur));
10524
10974
  }
10525
10975
  const reused = session.staticDedupCount ?? 0;
10526
10976
  if (session.staticFrames && reused > 0) {
@@ -10801,11 +11251,11 @@ import {
10801
11251
  openSync,
10802
11252
  readFileSync as readFileSync4,
10803
11253
  readdirSync as readdirSync3,
10804
- statSync as statSync3,
11254
+ statSync as statSync2,
10805
11255
  writeFileSync as writeFileSync2,
10806
11256
  writeSync
10807
11257
  } from "fs";
10808
- import { join as join9, dirname as dirname3, extname, resolve } from "path";
11258
+ import { join as join9, dirname as dirname4, extname, resolve as resolve2 } from "path";
10809
11259
 
10810
11260
  // ../engine/src/utils/gpuEncoder.ts
10811
11261
  import { spawn as spawn4 } from "child_process";
@@ -11435,7 +11885,7 @@ function frameReadFailure(stderr, framePattern, startNumber, framesRead, frameCo
11435
11885
  var secondsReader = (onSeconds) => onSeconds && ffmpegStatsReader(({ seconds }) => seconds !== void 0 && onSeconds(seconds));
11436
11886
  async function encodeFramesFromDir(framesDir, framePattern, outputPath, options, signal, config, onFramesEncoded) {
11437
11887
  const startTime = Date.now();
11438
- const outputDir = dirname3(outputPath);
11888
+ const outputDir = dirname4(outputPath);
11439
11889
  if (!existsSync6(outputDir)) mkdirSync2(outputDir, { recursive: true });
11440
11890
  const files = readdirSync3(framesDir).filter((f) => f.match(/\.(jpg|jpeg|png)$/i));
11441
11891
  const frameCount = files.length;
@@ -11492,7 +11942,7 @@ async function encodeFramesFromDir(framesDir, framePattern, outputPath, options,
11492
11942
  failureReason: isExternalFfmpegInterruption(result) ? "external_interruption" : void 0
11493
11943
  };
11494
11944
  }
11495
- const fileSize = existsSync6(outputPath) ? statSync3(outputPath).size : 0;
11945
+ const fileSize = existsSync6(outputPath) ? statSync2(outputPath).size : 0;
11496
11946
  return {
11497
11947
  success: true,
11498
11948
  outputPath,
@@ -11511,7 +11961,7 @@ var concatListSeq = 0;
11511
11961
  function writeConcatList(dir, inputPaths) {
11512
11962
  concatListSeq += 1;
11513
11963
  const listPath = join9(dir, `concat-list-${process.pid}-${concatListSeq}.txt`);
11514
- const body = inputPaths.map((p) => `file '${resolve(p).replace(/'/g, "'\\''")}'`).join("\n");
11964
+ const body = inputPaths.map((p) => `file '${resolve2(p).replace(/'/g, "'\\''")}'`).join("\n");
11515
11965
  writeFileSync2(listPath, body, "utf-8");
11516
11966
  return listPath;
11517
11967
  }
@@ -11520,8 +11970,8 @@ async function concatVideoFiles(inputPaths, outputPath, signal, config) {
11520
11970
  if (firstInput === void 0) {
11521
11971
  return { success: false, error: "concatVideoFiles: no inputs", externalInterruption: false };
11522
11972
  }
11523
- mkdirSync2(dirname3(outputPath), { recursive: true });
11524
- const listPath = writeConcatList(dirname3(firstInput), inputPaths);
11973
+ mkdirSync2(dirname4(outputPath), { recursive: true });
11974
+ const listPath = writeConcatList(dirname4(firstInput), inputPaths);
11525
11975
  const encodeTimeout = config?.ffmpegEncodeTimeout ?? DEFAULT_CONFIG.ffmpegEncodeTimeout;
11526
11976
  const result = await runFfmpeg(buildConcatArgs(listPath, outputPath), {
11527
11977
  signal,
@@ -11553,8 +12003,8 @@ async function encodeFramesChunkedConcat(framesDir, framePattern, outputPath, op
11553
12003
  }
11554
12004
  const chunkSize = Math.max(30, Math.floor(chunkSizeFrames));
11555
12005
  const chunkCount = Math.ceil(files.length / chunkSize);
11556
- mkdirSync2(dirname3(outputPath), { recursive: true });
11557
- const chunkDir = createStagingDir(dirname3(outputPath), "chunk-encode-");
12006
+ mkdirSync2(dirname4(outputPath), { recursive: true });
12007
+ const chunkDir = createStagingDir(dirname4(outputPath), "chunk-encode-");
11558
12008
  const chunkPaths = [];
11559
12009
  for (let i = 0; i < chunkCount; i++) {
11560
12010
  if (signal?.aborted) {
@@ -11635,7 +12085,7 @@ async function encodeFramesChunkedConcat(framesDir, framePattern, outputPath, op
11635
12085
  failureReason: concatResult.externalInterruption ? "external_interruption" : void 0
11636
12086
  };
11637
12087
  }
11638
- const fileSize = existsSync6(outputPath) ? statSync3(outputPath).size : 0;
12088
+ const fileSize = existsSync6(outputPath) ? statSync2(outputPath).size : 0;
11639
12089
  return {
11640
12090
  success: true,
11641
12091
  outputPath,
@@ -11645,7 +12095,7 @@ async function encodeFramesChunkedConcat(framesDir, framePattern, outputPath, op
11645
12095
  };
11646
12096
  }
11647
12097
  async function muxVideoWithAudio(videoPath, audioPath, outputPath, signal, config, fps, onSecondsWritten) {
11648
- const outputDir = dirname3(outputPath);
12098
+ const outputDir = dirname4(outputPath);
11649
12099
  if (!existsSync6(outputDir)) mkdirSync2(outputDir, { recursive: true });
11650
12100
  const outputExtension = extname(outputPath).toLowerCase();
11651
12101
  const isWebm = outputExtension === ".webm";
@@ -11868,8 +12318,8 @@ function quantizationTableError(buffer, start, end) {
11868
12318
  // ../engine/src/services/streamingEncoder.ts
11869
12319
  import { spawn as spawn5 } from "child_process";
11870
12320
  import { once } from "events";
11871
- import { existsSync as existsSync7, mkdirSync as mkdirSync3, statSync as statSync4 } from "fs";
11872
- import { dirname as dirname4 } from "path";
12321
+ import { existsSync as existsSync7, mkdirSync as mkdirSync3, statSync as statSync3 } from "fs";
12322
+ import { dirname as dirname5 } from "path";
11873
12323
  function createFrameReorderBuffer(startFrame, endFrame) {
11874
12324
  let cursor = startFrame;
11875
12325
  let aborted = null;
@@ -12145,7 +12595,7 @@ function spawnFfmpegStream(outputPath, args, {
12145
12595
  config,
12146
12596
  checkFrame
12147
12597
  }) {
12148
- const outputDir = dirname4(outputPath);
12598
+ const outputDir = dirname5(outputPath);
12149
12599
  if (!existsSync7(outputDir)) mkdirSync3(outputDir, { recursive: true });
12150
12600
  const ffmpeg = spawn5(getFfmpegBinary(), args, {
12151
12601
  stdio: ["pipe", "pipe", "pipe"],
@@ -12265,554 +12715,272 @@ FFmpeg stopped after ${streamingTimeout} ms without consuming a frame.` : "";
12265
12715
  fileSize: 0,
12266
12716
  error: `${formatFfmpegError(exitCode, stderr)}${inactivitySuffix}`,
12267
12717
  failureReason: isExternalFfmpegInterruption({
12268
- exitCode,
12269
- signal: exitSignal,
12270
- stderr,
12271
- terminationReason
12272
- }) ? "external_interruption" : void 0
12273
- };
12274
- }
12275
- const fileSize = existsSync7(outputPath) ? statSync4(outputPath).size : 0;
12276
- return { success: true, durationMs, fileSize, drainWaitMs };
12277
- },
12278
- getExitStatus: () => exitStatus,
12279
- getExitError: () => {
12280
- if (exitStatus !== "error") return void 0;
12281
- return formatFfmpegError(exitCode, stderr);
12282
- },
12283
- getExitFailureReason: () => {
12284
- if (exitStatus !== "error") return void 0;
12285
- return isExternalFfmpegInterruption({
12286
- exitCode,
12287
- signal: exitSignal,
12288
- stderr,
12289
- terminationReason
12290
- }) ? "external_interruption" : void 0;
12291
- }
12292
- };
12293
- return encoder;
12294
- }
12295
-
12296
- // ../engine/src/services/chunkStreamingEncoder.ts
12297
- var BT709_LIMITED = {
12298
- primaries: 1,
12299
- transfer: 1,
12300
- matrix: 1,
12301
- fullRange: false
12302
- };
12303
- function buildChunkStreamingArgs(options, outputPath) {
12304
- const { primaries, transfer, matrix, fullRange } = options.colour ?? BT709_LIMITED;
12305
- const vui = [
12306
- `colour_primaries=${primaries}`,
12307
- `transfer_characteristics=${transfer}`,
12308
- `matrix_coefficients=${matrix}`,
12309
- `video_full_range_flag=${fullRange ? 1 : 0}`
12310
- ].join(":");
12311
- const args = ["-f", "h264", "-framerate", fpsToFfmpegArg(options.fps), "-i", "-"];
12312
- args.push("-c:v", "copy", "-bsf:v", `h264_metadata=${vui}`);
12313
- args.push(
12314
- ...["-colorspace:v", "bt709", "-color_primaries:v", "bt709", "-color_trc:v", "bt709"],
12315
- ...["-color_range", fullRange ? "pc" : "tv"],
12316
- ...["-video_track_timescale", "90000", "-avoid_negative_ts", "make_zero"]
12317
- );
12318
- appendRenderProvenanceArgs(args, outputPath);
12319
- args.push("-y", outputPath);
12320
- return args;
12321
- }
12322
- function spawnChunkStreamingEncoder(outputPath, options, signal, config) {
12323
- return spawnFfmpegStream(outputPath, buildChunkStreamingArgs(options, outputPath), {
12324
- signal,
12325
- config
12326
- });
12327
- }
12328
-
12329
- // ../engine/src/services/inPageEncodeEligibility.ts
12330
- function resolveInPageEncode(input) {
12331
- const blocker = [
12332
- [!input.enabled, "disabled"],
12333
- [input.captureMode !== "drawelement", "capture is not drawElement"],
12334
- [input.format !== "mp4", "output is not mp4"],
12335
- [input.codec !== "h264", "codec is not h264"],
12336
- [input.hdr, "hdr"],
12337
- [input.transparent, "transparent"],
12338
- [input.workers !== 1, "parallel workers"],
12339
- [input.hls, "hls"],
12340
- [input.videoLayer, "video layer passthrough"],
12341
- [!input.encoderSupported, "page encoder unsupported"]
12342
- ].find(([blocked]) => blocked);
12343
- return blocker ? { eligible: false, reason: blocker[1] } : { eligible: true };
12344
- }
12345
-
12346
- // ../core/dist/audioGroups.js
12347
- var HF_AUDIO_GROUP_TAG = "hf-audio-group";
12348
- var HF_AUDIO_GROUP_ATTR = "data-audio-group";
12349
- function readAudioGroupVolume(el) {
12350
- const raw = el?.getAttribute("data-volume");
12351
- const parsed = raw ? parseFloat(raw) : 1;
12352
- return Number.isFinite(parsed) ? parsed : 1;
12353
- }
12354
- function buildGroup(id, memberIds, el) {
12355
- const fxChain = el?.getAttribute(HF_AUDIO_FX_ATTR);
12356
- const automation = el?.getAttribute(HF_AUDIO_AUTOMATION_ATTR);
12357
- return {
12358
- id,
12359
- label: el?.getAttribute("data-label") || id,
12360
- memberIds,
12361
- ...fxChain ? { fxChain } : {},
12362
- ...automation ? { automation } : {},
12363
- volume: readAudioGroupVolume(el),
12364
- hidden: el?.hasAttribute("data-hidden") ?? false
12365
- };
12366
- }
12367
- function resolveMasterBusElement(root) {
12368
- const first = root.querySelector("[data-composition-id]");
12369
- return first && !first.parentElement?.closest("[data-composition-id]") ? first : null;
12370
- }
12371
- function readMasterFxChain(root) {
12372
- return resolveMasterBusElement(root)?.getAttribute(HF_AUDIO_FX_ATTR) || void 0;
12373
- }
12374
- function resolveAudioGroups(root) {
12375
- const membersByGroup = /* @__PURE__ */ new Map();
12376
- const candidates = root.querySelectorAll(`audio[${HF_AUDIO_GROUP_ATTR}], video[${HF_AUDIO_GROUP_ATTR}]`);
12377
- for (const member of candidates) {
12378
- if (!isGroupableMember(member))
12379
- continue;
12380
- const groupId = member.getAttribute(AUDIO_GROUP_RENDER_ID_ATTR) ?? member.getAttribute(HF_AUDIO_GROUP_ATTR);
12381
- if (!groupId || !member.id)
12382
- continue;
12383
- const members = membersByGroup.get(groupId);
12384
- if (members)
12385
- members.push(member.id);
12386
- else
12387
- membersByGroup.set(groupId, [member.id]);
12388
- }
12389
- const groupElements = /* @__PURE__ */ new Map();
12390
- for (const el of root.querySelectorAll(HF_AUDIO_GROUP_TAG)) {
12391
- const key = el.getAttribute(MEDIA_RENDER_ID_ATTR) ?? el.id;
12392
- if (key)
12393
- groupElements.set(key, el);
12394
- }
12395
- const groups = [];
12396
- for (const [id, memberIds] of membersByGroup) {
12397
- groups.push(buildGroup(id, memberIds, groupElements.get(id)));
12398
- }
12399
- return groups;
12400
- }
12401
- function isGroupableMember(el) {
12402
- if (el.tagName.toLowerCase() === "audio")
12403
- return true;
12404
- return typeof el.hasAttribute === "function" && isAudibleVideoElement(el);
12405
- }
12406
-
12407
- // ../engine/src/services/mediaHidden.ts
12408
- function isSelfOrAncestorHidden(el) {
12409
- for (let current = el; current; current = current.parentElement) {
12410
- if (current.hasAttribute("data-hidden")) return true;
12411
- }
12412
- return false;
12413
- }
12414
- function memberGroupKey(el) {
12415
- return el.getAttribute(AUDIO_GROUP_RENDER_ID_ATTR) ?? el.getAttribute(HF_AUDIO_GROUP_ATTR);
12416
- }
12417
- function audioGroupsById(document2) {
12418
- return new Map(resolveAudioGroups(document2).map((group) => [group.id, group]));
12419
- }
12420
- function isMemberGroupHidden(groupsById, el) {
12421
- const groupId = memberGroupKey(el);
12422
- return groupId ? groupsById.get(groupId)?.hidden ?? false : false;
12423
- }
12424
-
12425
- // ../engine/src/services/videoFrameExtractor.ts
12426
- import { copyFileSync as copyFileSync2, existsSync as existsSync11, linkSync as linkSync2, mkdirSync as mkdirSync6, rmSync as rmSync5 } from "fs";
12427
- import { basename as basename2, isAbsolute as isAbsolute2, join as join13, normalize, relative as relative2, win32 } from "path";
12428
-
12429
- // ../engine/src/utils/concurrencyLimit.ts
12430
- function createConcurrencyLimit(limit) {
12431
- let active = 0;
12432
- const waiting = [];
12433
- const waitForSlot = (signal) => new Promise((resolve3) => {
12434
- const granted = () => {
12435
- signal?.removeEventListener("abort", aborted);
12436
- resolve3(true);
12437
- };
12438
- const aborted = () => {
12439
- waiting.splice(waiting.indexOf(granted), 1);
12440
- resolve3(false);
12441
- };
12442
- waiting.push(granted);
12443
- signal?.addEventListener("abort", aborted, { once: true });
12444
- });
12445
- return async (task, signal) => {
12446
- if (signal?.aborted) return task();
12447
- if (active < limit) active++;
12448
- else if (!await waitForSlot(signal)) return task();
12449
- try {
12450
- return await task();
12451
- } finally {
12452
- const next = waiting.shift();
12453
- if (next) next();
12454
- else active--;
12455
- }
12456
- };
12457
- }
12458
-
12459
- // ../engine/src/utils/assetRoots.ts
12460
- import { existsSync as existsSync8 } from "fs";
12461
- function isInsideAssetRoots(path, roots) {
12462
- if (roots.some((root) => isSafePath(root, path))) return true;
12463
- return !existsSync8(path) && roots.some((root) => isWithinProjectRoot(root, path));
12464
- }
12465
-
12466
- // ../engine/src/services/mediaTimelineWindow.ts
12467
- function isKnownInactiveTimelineWindow(element, resolvedStart) {
12468
- const duration = parseStrictFiniteTimingNumber(element.getAttribute("data-duration"));
12469
- if (duration != null && duration <= 0) return true;
12470
- const end = parseStrictFiniteTimingNumber(element.getAttribute("data-end"));
12471
- return end != null && end <= resolvedStart;
12472
- }
12473
-
12474
- // ../engine/src/utils/alphaPlaneProbe.ts
12475
- import { mkdtempSync as mkdtempSync3, readFileSync as readFileSync5, rmSync as rmSync2 } from "fs";
12476
- import { tmpdir as tmpdir4 } from "os";
12477
- import { join as join10 } from "path";
12478
- var BYTES_PER_SAMPLE_FRAME = 8 * 8 * 4;
12479
- var MAX_SAMPLE_BYTES = BYTES_PER_SAMPLE_FRAME * 3;
12480
- function sampledRgbaAlphaIsFullyOpaque(buf) {
12481
- if (buf.length === 0 || buf.length > MAX_SAMPLE_BYTES || buf.length % BYTES_PER_SAMPLE_FRAME !== 0) {
12482
- return void 0;
12483
- }
12484
- for (let i = 3; i < buf.length; i += 4) {
12485
- if (buf[i] !== 255) return false;
12486
- }
12487
- return true;
12488
- }
12489
- async function probeInputAlphaPlane(videoPath, decoder, signal) {
12490
- let probeDir;
12491
- try {
12492
- probeDir = mkdtempSync3(join10(tmpdir4(), "hf-alpha-probe-"));
12493
- const samplePath = join10(probeDir, "alpha.raw");
12494
- const result = await runFfmpeg(
12495
- [
12496
- "-v",
12497
- "error",
12498
- "-c:v",
12499
- decoder,
12500
- "-i",
12501
- videoPath,
12502
- "-frames:v",
12503
- "3",
12504
- "-vf",
12505
- "scale=8:8",
12506
- "-pix_fmt",
12507
- "rgba",
12508
- "-f",
12509
- "rawvideo",
12510
- samplePath
12511
- ],
12512
- { timeout: 3e4, signal }
12513
- );
12514
- if (!result.success) return void 0;
12515
- return sampledRgbaAlphaIsFullyOpaque(readFileSync5(samplePath));
12516
- } catch {
12517
- return void 0;
12518
- } finally {
12519
- if (probeDir) rmSync2(probeDir, { recursive: true, force: true });
12520
- }
12521
- }
12522
- function inputAlphaOpaqueWarning(src) {
12523
- return `[hyperframes:render] WARNING: video src="${src}" declares an alpha channel but its first frames decode fully opaque. If it should be transparent, re-export it with an alpha pixel format and avoid remuxing afterward, which can drop the alpha while keeping the tag.
12524
- `;
12718
+ exitCode,
12719
+ signal: exitSignal,
12720
+ stderr,
12721
+ terminationReason
12722
+ }) ? "external_interruption" : void 0
12723
+ };
12724
+ }
12725
+ const fileSize = existsSync7(outputPath) ? statSync3(outputPath).size : 0;
12726
+ return { success: true, durationMs, fileSize, drainWaitMs };
12727
+ },
12728
+ getExitStatus: () => exitStatus,
12729
+ getExitError: () => {
12730
+ if (exitStatus !== "error") return void 0;
12731
+ return formatFfmpegError(exitCode, stderr);
12732
+ },
12733
+ getExitFailureReason: () => {
12734
+ if (exitStatus !== "error") return void 0;
12735
+ return isExternalFfmpegInterruption({
12736
+ exitCode,
12737
+ signal: exitSignal,
12738
+ stderr,
12739
+ terminationReason
12740
+ }) ? "external_interruption" : void 0;
12741
+ }
12742
+ };
12743
+ return encoder;
12525
12744
  }
12526
12745
 
12527
- // ../engine/src/utils/notMediaPayload.ts
12528
- import { createHash } from "crypto";
12529
- import { constants } from "fs";
12530
- import { open as openFile } from "fs/promises";
12531
- import { dirname as dirname5, isAbsolute, relative, resolve as resolve2 } from "path";
12532
- var NOT_MEDIA_PAYLOAD = "NOT_MEDIA_PAYLOAD";
12533
- var MAX_LISTED_FINGERPRINTS = 8;
12534
- var NotMediaPayloadError = class extends Error {
12535
- code = NOT_MEDIA_PAYLOAD;
12536
- owner = "user";
12537
- retryable = false;
12538
- elementFingerprints;
12539
- constructor(elementFingerprints) {
12540
- const listed2 = elementFingerprints.slice(0, MAX_LISTED_FINGERPRINTS).join(",");
12541
- const elided = elementFingerprints.length - MAX_LISTED_FINGERPRINTS;
12542
- super(
12543
- `${elementFingerprints.length} media source(s) are text documents (HTML/XML/JSON, or a playlist naming files outside its own folder), not media containers [elements=${listed2}${elided > 0 ? `,+${elided}` : ""}]. Either an unresolved nested-composition preview URL was authored as a media src, or the source answered with an error page or API error body carrying a success status.`
12544
- );
12545
- this.name = "NotMediaPayloadError";
12546
- this.elementFingerprints = elementFingerprints;
12547
- }
12746
+ // ../engine/src/services/chunkStreamingEncoder.ts
12747
+ var BT709_LIMITED = {
12748
+ primaries: 1,
12749
+ transfer: 1,
12750
+ matrix: 1,
12751
+ fullRange: false
12548
12752
  };
12549
- function fingerprintElementId(elementId) {
12550
- return createHash("sha256").update(elementId).digest("hex").slice(0, 16);
12551
- }
12552
- var SNIFF_BYTES = 512;
12553
- var DOCUMENT_OPENING_BYTES = /* @__PURE__ */ new Set([60, 123, 91]);
12554
- var SKIPPABLE_LEADING_BYTES = /* @__PURE__ */ new Set([0, 9, 10, 11, 12, 13, 32]);
12555
- var BYTE_ORDER_MARKS = [
12556
- Buffer.from([239, 187, 191]),
12557
- // UTF-8
12558
- Buffer.from([255, 254]),
12559
- // UTF-16 LE
12560
- Buffer.from([254, 255])
12561
- // UTF-16 BE
12562
- ];
12563
- function byteOrderMarkLength(head) {
12564
- for (const mark of BYTE_ORDER_MARKS) {
12565
- if (head.length >= mark.length && head.subarray(0, mark.length).equals(mark)) {
12566
- return mark.length;
12567
- }
12568
- }
12569
- return 0;
12570
- }
12571
- async function readAt(fh, bytes, position) {
12572
- const buf = Buffer.alloc(bytes);
12573
- let filled = 0;
12574
- while (filled < buf.length) {
12575
- const { bytesRead } = await fh.read(buf, filled, buf.length - filled, position + filled);
12576
- if (bytesRead === 0) break;
12577
- filled += bytesRead;
12578
- }
12579
- return buf.subarray(0, filled);
12753
+ function buildChunkStreamingArgs(options, outputPath) {
12754
+ const { primaries, transfer, matrix, fullRange } = options.colour ?? BT709_LIMITED;
12755
+ const vui = [
12756
+ `colour_primaries=${primaries}`,
12757
+ `transfer_characteristics=${transfer}`,
12758
+ `matrix_coefficients=${matrix}`,
12759
+ `video_full_range_flag=${fullRange ? 1 : 0}`
12760
+ ].join(":");
12761
+ const args = ["-f", "h264", "-framerate", fpsToFfmpegArg(options.fps), "-i", "-"];
12762
+ args.push("-c:v", "copy", "-bsf:v", `h264_metadata=${vui}`);
12763
+ args.push(
12764
+ ...["-colorspace:v", "bt709", "-color_primaries:v", "bt709", "-color_trc:v", "bt709"],
12765
+ ...["-color_range", fullRange ? "pc" : "tv"],
12766
+ ...["-video_track_timescale", "90000", "-avoid_negative_ts", "make_zero"]
12767
+ );
12768
+ appendRenderProvenanceArgs(args, outputPath);
12769
+ args.push("-y", outputPath);
12770
+ return args;
12580
12771
  }
12581
- var OPEN_WITHOUT_WAITING = constants.O_RDONLY | (constants.O_NONBLOCK ?? 0);
12582
- async function openRegular(path) {
12583
- const fh = await openFile(path, OPEN_WITHOUT_WAITING);
12584
- try {
12585
- const stats = await fh.stat();
12586
- if (stats.isFile() || stats.isDirectory()) return fh;
12587
- } catch (error) {
12588
- await fh.close().catch(() => {
12589
- });
12590
- throw error;
12591
- }
12592
- await fh.close().catch(() => {
12772
+ function spawnChunkStreamingEncoder(outputPath, options, signal, config) {
12773
+ return spawnFfmpegStream(outputPath, buildChunkStreamingArgs(options, outputPath), {
12774
+ signal,
12775
+ config
12593
12776
  });
12594
- return null;
12595
- }
12596
- async function readHead(filePath) {
12597
- const fh = await openRegular(filePath);
12598
- if (!fh) return null;
12599
- try {
12600
- const { size } = await fh.stat();
12601
- return { head: await readAt(fh, SNIFF_BYTES, 0), fileSize: size };
12602
- } finally {
12603
- await fh.close().catch(() => {
12604
- });
12605
- }
12606
- }
12607
- var FIRST_BOX_TYPES = /* @__PURE__ */ new Set([
12608
- "ftyp",
12609
- "styp",
12610
- "free",
12611
- "skip",
12612
- "wide",
12613
- "uuid",
12614
- "pdin",
12615
- "moov",
12616
- "mdat",
12617
- "moof"
12618
- ]);
12619
- var BOX_TYPE = /^[\x21-\x7e\xa9][\x21-\x7e]{3}$/;
12620
- function boxLength(head, offset) {
12621
- const size = head.readUInt32BE(offset);
12622
- if (size !== 1) return size >= 8 ? size : -1;
12623
- if (offset + 16 > head.length) return -1;
12624
- const largeSize = Number(head.readBigUInt64BE(offset + 8));
12625
- return largeSize >= 16 ? largeSize : -1;
12626
- }
12627
- function boxEnd(head, offset, fileSize) {
12628
- if (offset + 8 > head.length || !BOX_TYPE.test(head.toString("latin1", offset + 4, offset + 8))) {
12629
- return -1;
12630
- }
12631
- if (head.readUInt32BE(offset) === 0) return fileSize;
12632
- const length = boxLength(head, offset);
12633
- return length >= 0 && offset + length <= fileSize ? offset + length : -1;
12634
12777
  }
12635
- function opensWithMediaBox(head, fileSize) {
12636
- if (!FIRST_BOX_TYPES.has(head.toString("latin1", 4, 8))) return false;
12637
- let offset = boxEnd(head, 0, fileSize);
12638
- while (offset >= 0 && offset < fileSize && offset + 16 <= head.length) {
12639
- offset = boxEnd(head, offset, fileSize);
12640
- }
12641
- return offset >= 0;
12778
+
12779
+ // ../engine/src/services/inPageEncodeEligibility.ts
12780
+ function resolveInPageEncode(input) {
12781
+ const blocker = [
12782
+ [!input.enabled, "disabled"],
12783
+ [input.captureMode !== "drawelement", "capture is not drawElement"],
12784
+ [input.format !== "mp4", "output is not mp4"],
12785
+ [input.codec !== "h264", "codec is not h264"],
12786
+ [input.hdr, "hdr"],
12787
+ [input.transparent, "transparent"],
12788
+ [input.workers !== 1, "parallel workers"],
12789
+ [input.hls, "hls"],
12790
+ [input.videoLayer, "video layer passthrough"],
12791
+ [!input.encoderSupported, "page encoder unsupported"]
12792
+ ].find(([blocked]) => blocked);
12793
+ return blocker ? { eligible: false, reason: blocker[1] } : { eligible: true };
12642
12794
  }
12643
- function startsWithDocumentByte(head, fileSize) {
12644
- if (opensWithMediaBox(head, fileSize)) return false;
12645
- for (let index = byteOrderMarkLength(head); index < head.length; index++) {
12646
- const byte = head[index];
12647
- if (byte === void 0) break;
12648
- if (SKIPPABLE_LEADING_BYTES.has(byte)) continue;
12649
- return DOCUMENT_OPENING_BYTES.has(byte);
12650
- }
12651
- return false;
12795
+
12796
+ // ../core/dist/audioGroups.js
12797
+ var HF_AUDIO_GROUP_TAG = "hf-audio-group";
12798
+ var HF_AUDIO_GROUP_ATTR = "data-audio-group";
12799
+ function readAudioGroupVolume(el) {
12800
+ const raw = el?.getAttribute("data-volume");
12801
+ const parsed = raw ? parseFloat(raw) : 1;
12802
+ return Number.isFinite(parsed) ? parsed : 1;
12652
12803
  }
12653
- async function isNotMediaPayload(filePath) {
12654
- try {
12655
- const sniffed = await readHead(filePath);
12656
- return !sniffed || startsWithDocumentByte(sniffed.head, sniffed.fileSize) || await playlistLeavesItsFolder(filePath);
12657
- } catch {
12658
- return false;
12659
- }
12804
+ function buildGroup(id, memberIds, el) {
12805
+ const fxChain = el?.getAttribute(HF_AUDIO_FX_ATTR);
12806
+ const automation = el?.getAttribute(HF_AUDIO_AUTOMATION_ATTR);
12807
+ return {
12808
+ id,
12809
+ label: el?.getAttribute("data-label") || id,
12810
+ memberIds,
12811
+ ...fxChain ? { fxChain } : {},
12812
+ ...automation ? { automation } : {},
12813
+ volume: readAudioGroupVolume(el),
12814
+ hidden: el?.hasAttribute("data-hidden") ?? false
12815
+ };
12660
12816
  }
12661
- async function assertMediaPayload(filePath, elementId) {
12662
- if (await isNotMediaPayload(filePath)) {
12663
- throw new NotMediaPayloadError([fingerprintElementId(elementId)]);
12664
- }
12817
+ function resolveMasterBusElement(root) {
12818
+ const first = root.querySelector("[data-composition-id]");
12819
+ return first && !first.parentElement?.closest("[data-composition-id]") ? first : null;
12665
12820
  }
12666
- var MAX_PLAYLIST_BYTES = 8 * 1024 * 1024;
12667
- var MAX_PLAYLIST_DEPTH = 8;
12668
- var HTTP_URL = /^https?:\/\//i;
12669
- var OTHER_SCHEME = /^[a-z][a-z0-9+.-]+:/i;
12670
- var DRIVE_PATH = /^[a-z]:[\\/]/i;
12671
- var MAX_HLS_LINE_BYTES = 4095;
12672
- var ATTRIBUTE_GAP = /[\t\n\v\f\r ,]/;
12673
- function hlsEntries(body) {
12674
- const names = /* @__PURE__ */ new Set();
12675
- for (const raw of body.replaceAll("\0", "\n").split(/[\r\n]/)) {
12676
- for (const whole of /* @__PURE__ */ new Set([raw, raw.slice(0, MAX_HLS_LINE_BYTES)])) {
12677
- const line = whole.replace(/[\t\v\f ]+$/, "");
12678
- const found = line.startsWith("#") ? attributeUris(line) : [line, line.trim()];
12679
- for (const name of found) if (name) names.add(name);
12680
- }
12681
- }
12682
- return [...names];
12821
+ function readMasterFxChain(root) {
12822
+ return resolveMasterBusElement(root)?.getAttribute(HF_AUDIO_FX_ATTR) || void 0;
12683
12823
  }
12684
- function attributeUris(line) {
12685
- const uris = [];
12686
- let at = line.indexOf(":") + 1;
12687
- while (at > 0 && at < line.length) {
12688
- while (at < line.length && ATTRIBUTE_GAP.test(line[at])) at++;
12689
- const equals = line.indexOf("=", at);
12690
- if (equals < 0) break;
12691
- const [value, next] = attributeValue(line, equals + 1);
12692
- if (line.slice(at, equals).toUpperCase() === "URI") uris.push(value);
12693
- at = next;
12824
+ function resolveAudioGroups(root) {
12825
+ const membersByGroup = /* @__PURE__ */ new Map();
12826
+ const candidates = root.querySelectorAll(`audio[${HF_AUDIO_GROUP_ATTR}], video[${HF_AUDIO_GROUP_ATTR}]`);
12827
+ for (const member of candidates) {
12828
+ if (!isGroupableMember(member))
12829
+ continue;
12830
+ const groupId = member.getAttribute(AUDIO_GROUP_RENDER_ID_ATTR) ?? member.getAttribute(HF_AUDIO_GROUP_ATTR);
12831
+ if (!groupId || !member.id)
12832
+ continue;
12833
+ const members = membersByGroup.get(groupId);
12834
+ if (members)
12835
+ members.push(member.id);
12836
+ else
12837
+ membersByGroup.set(groupId, [member.id]);
12694
12838
  }
12695
- return uris;
12696
- }
12697
- function attributeValue(line, at) {
12698
- if (line[at] !== '"') {
12699
- let end = at;
12700
- while (end < line.length && !ATTRIBUTE_GAP.test(line[end])) end++;
12701
- return [line.slice(at, end), end];
12839
+ const groupElements = /* @__PURE__ */ new Map();
12840
+ for (const el of root.querySelectorAll(HF_AUDIO_GROUP_TAG)) {
12841
+ const key = el.getAttribute(MEDIA_RENDER_ID_ATTR) ?? el.id;
12842
+ if (key)
12843
+ groupElements.set(key, el);
12702
12844
  }
12703
- let value = "";
12704
- let index = at + 1;
12705
- for (; index < line.length && line[index] !== '"'; index++) {
12706
- if (line[index] === "\\") {
12707
- if (index + 1 >= line.length) break;
12708
- index++;
12709
- }
12710
- value += line[index];
12845
+ const groups = [];
12846
+ for (const [id, memberIds] of membersByGroup) {
12847
+ groups.push(buildGroup(id, memberIds, groupElements.get(id)));
12711
12848
  }
12712
- return [value, line[index] === '"' ? index + 1 : index];
12849
+ return groups;
12713
12850
  }
12714
- var UTF8_BOM = "\xEF\xBB\xBF";
12715
- function playlistEntries(text) {
12716
- const body = (text.startsWith(UTF8_BOM) ? text.slice(UTF8_BOM.length) : text).trimStart();
12717
- if (body.startsWith("#EXTM3U")) return hlsEntries(body);
12718
- if (/^ffconcat\s+version/i.test(body)) {
12719
- return body.split(/\r?\n/).flatMap((raw) => {
12720
- const match = /^\s*file\s+(.*)$/.exec(raw);
12721
- if (!match) return [];
12722
- const value = match[1].trim();
12723
- return [value.startsWith("'") ? value.slice(1, -1).replace(/\\(.)/g, "$1") : value];
12724
- });
12851
+ function isGroupableMember(el) {
12852
+ if (el.tagName.toLowerCase() === "audio")
12853
+ return true;
12854
+ return typeof el.hasAttribute === "function" && isAudibleVideoElement(el);
12855
+ }
12856
+
12857
+ // ../engine/src/services/mediaHidden.ts
12858
+ function isSelfOrAncestorHidden(el) {
12859
+ for (let current = el; current; current = current.parentElement) {
12860
+ if (current.hasAttribute("data-hidden")) return true;
12725
12861
  }
12726
- return void 0;
12862
+ return false;
12727
12863
  }
12728
- function entryLeavesFolder(entry, base, folder) {
12729
- if (HTTP_URL.test(entry)) return false;
12730
- if (OTHER_SCHEME.test(entry) && !DRIVE_PATH.test(entry)) return true;
12731
- return [entry, percentDecoded(entry)].some((path) => {
12732
- if (isAbsolute(path) || DRIVE_PATH.test(path) || path.startsWith("\\")) return true;
12733
- const inside = relative(folder, resolve2(base, path));
12734
- return inside === ".." || inside.startsWith("../") || inside.startsWith("..\\") || isAbsolute(inside);
12864
+ function memberGroupKey(el) {
12865
+ return el.getAttribute(AUDIO_GROUP_RENDER_ID_ATTR) ?? el.getAttribute(HF_AUDIO_GROUP_ATTR);
12866
+ }
12867
+ function audioGroupsById(document2) {
12868
+ return new Map(resolveAudioGroups(document2).map((group) => [group.id, group]));
12869
+ }
12870
+ function isMemberGroupHidden(groupsById, el) {
12871
+ const groupId = memberGroupKey(el);
12872
+ return groupId ? groupsById.get(groupId)?.hidden ?? false : false;
12873
+ }
12874
+
12875
+ // ../engine/src/services/videoFrameExtractor.ts
12876
+ import { copyFileSync as copyFileSync2, existsSync as existsSync11, linkSync as linkSync2, mkdirSync as mkdirSync6, rmSync as rmSync5 } from "fs";
12877
+ import { basename as basename3, isAbsolute as isAbsolute2, join as join13, normalize, relative as relative2, win32 } from "path";
12878
+
12879
+ // ../engine/src/utils/concurrencyLimit.ts
12880
+ function createConcurrencyLimit(limit) {
12881
+ let active = 0;
12882
+ const waiting = [];
12883
+ const waitForSlot = (signal) => new Promise((resolve3) => {
12884
+ const granted = () => {
12885
+ signal?.removeEventListener("abort", aborted);
12886
+ resolve3(true);
12887
+ };
12888
+ const aborted = () => {
12889
+ waiting.splice(waiting.indexOf(granted), 1);
12890
+ resolve3(false);
12891
+ };
12892
+ waiting.push(granted);
12893
+ signal?.addEventListener("abort", aborted, { once: true });
12735
12894
  });
12895
+ return async (task, signal) => {
12896
+ if (signal?.aborted) return task();
12897
+ if (active < limit) active++;
12898
+ else if (!await waitForSlot(signal)) return task();
12899
+ try {
12900
+ return await task();
12901
+ } finally {
12902
+ const next = waiting.shift();
12903
+ if (next) next();
12904
+ else active--;
12905
+ }
12906
+ };
12736
12907
  }
12737
- function percentDecoded(value) {
12738
- return value.replace(
12739
- /%([0-9a-f]{2})/gi,
12740
- (_escape, hex) => String.fromCharCode(Number.parseInt(hex, 16))
12741
- );
12908
+
12909
+ // ../engine/src/utils/assetRoots.ts
12910
+ import { existsSync as existsSync8 } from "fs";
12911
+ function isInsideAssetRoots(path, roots) {
12912
+ if (roots.some((root) => isSafePath(root, path))) return true;
12913
+ return !existsSync8(path) && roots.some((root) => isWithinProjectRoot(root, path));
12742
12914
  }
12743
- var asBytes = (path) => Buffer.from(path).toString("latin1");
12744
- async function playlistLeavesItsFolder(filePath, placedAt = filePath) {
12745
- const placed = asBytes(resolve2(placedAt));
12746
- const walk = { folder: dirname5(placed), seen: /* @__PURE__ */ new Set(), verdicts: /* @__PURE__ */ new Map() };
12747
- try {
12748
- return await listLeaves(asBytes(resolve2(filePath)), placed, walk, 0);
12749
- } catch {
12750
- return false;
12751
- }
12915
+ function isPrivateUnderAssetRoots(path, roots) {
12916
+ const holders = roots.filter((root) => isSafePath(root, path));
12917
+ return holders.length > 0 && holders.every((root) => isPrivateFileUnder(root, path, isStudioPrivatePath));
12752
12918
  }
12753
- var MAX_ID3_TAGS = 16;
12754
- function isId3Header(head) {
12755
- return head.length >= 10 && head.toString("latin1", 0, 3) === "ID3" && head[3] !== 255 && head[4] !== 255 && head.subarray(6, 10).every((byte) => byte < 128);
12919
+ function assetRootsRefusal(path, roots) {
12920
+ if (!isInsideAssetRoots(path, roots)) return "outside the project folder";
12921
+ return isPrivateUnderAssetRoots(path, roots) ? "a private project file" : null;
12756
12922
  }
12757
- async function textStart(fh, first) {
12758
- let offset = 0;
12759
- let head = first;
12760
- for (let tags = 0; tags <= MAX_ID3_TAGS; tags++) {
12761
- if (!isId3Header(head)) return offset;
12762
- const size = head[6] << 21 | head[7] << 14 | head[8] << 7 | head[9];
12763
- offset += 10 + size + (head[5] & 16 ? 10 : 0);
12764
- head = await readAt(fh, 10, offset);
12765
- }
12766
- return -1;
12923
+
12924
+ // ../engine/src/services/mediaTimelineWindow.ts
12925
+ function isKnownInactiveTimelineWindow(element, resolvedStart) {
12926
+ const duration = parseStrictFiniteTimingNumber(element.getAttribute("data-duration"));
12927
+ if (duration != null && duration <= 0) return true;
12928
+ const end = parseStrictFiniteTimingNumber(element.getAttribute("data-end"));
12929
+ return end != null && end <= resolvedStart;
12767
12930
  }
12768
- function startsAsPlaylist(head) {
12769
- const text = head.toString("utf8").replace(/^\uFEFF/, "").trimStart();
12770
- return text.startsWith("#EXTM3U") || /^ffconcat\s+version/i.test(text);
12931
+
12932
+ // ../engine/src/utils/alphaPlaneProbe.ts
12933
+ import { mkdtempSync as mkdtempSync3, readFileSync as readFileSync5, rmSync as rmSync2 } from "fs";
12934
+ import { tmpdir as tmpdir4 } from "os";
12935
+ import { join as join10 } from "path";
12936
+ var BYTES_PER_SAMPLE_FRAME = 8 * 8 * 4;
12937
+ var MAX_SAMPLE_BYTES = BYTES_PER_SAMPLE_FRAME * 3;
12938
+ function sampledRgbaAlphaIsFullyOpaque(buf) {
12939
+ if (buf.length === 0 || buf.length > MAX_SAMPLE_BYTES || buf.length % BYTES_PER_SAMPLE_FRAME !== 0) {
12940
+ return void 0;
12941
+ }
12942
+ for (let i = 3; i < buf.length; i += 4) {
12943
+ if (buf[i] !== 255) return false;
12944
+ }
12945
+ return true;
12771
12946
  }
12772
- async function readList(path) {
12773
- const fh = await openRegular(Buffer.from(path, "latin1"));
12774
- if (!fh) return true;
12947
+ async function probeInputAlphaPlane(videoPath, decoder, signal) {
12948
+ let probeDir;
12775
12949
  try {
12776
- const first = await readAt(fh, SNIFF_BYTES, 0);
12777
- const start = await textStart(fh, first);
12778
- if (start < 0) return true;
12779
- if (!startsAsPlaylist(start === 0 ? first : await readAt(fh, SNIFF_BYTES, start))) return null;
12780
- const body = await readAt(fh, MAX_PLAYLIST_BYTES + 1, start);
12781
- return body.length > MAX_PLAYLIST_BYTES ? true : body.toString("latin1");
12950
+ probeDir = mkdtempSync3(join10(tmpdir4(), "hf-alpha-probe-"));
12951
+ const samplePath = join10(probeDir, "alpha.raw");
12952
+ const result = await runFfmpeg(
12953
+ [
12954
+ "-v",
12955
+ "error",
12956
+ ...urlInputArgs(videoPath),
12957
+ "-c:v",
12958
+ decoder,
12959
+ "-i",
12960
+ videoPath,
12961
+ "-frames:v",
12962
+ "3",
12963
+ "-vf",
12964
+ "scale=8:8",
12965
+ "-pix_fmt",
12966
+ "rgba",
12967
+ "-f",
12968
+ "rawvideo",
12969
+ samplePath
12970
+ ],
12971
+ { timeout: 3e4, signal }
12972
+ );
12973
+ if (!result.success) return void 0;
12974
+ return sampledRgbaAlphaIsFullyOpaque(readFileSync5(samplePath));
12975
+ } catch {
12976
+ return void 0;
12782
12977
  } finally {
12783
- await fh.close().catch(() => {
12784
- });
12785
- }
12786
- }
12787
- var isMissing = (error) => ["ENOENT", "ENOTDIR", "ENAMETOOLONG"].includes(
12788
- error?.code ?? ""
12789
- );
12790
- async function listLeaves(readPath, path, walk, depth) {
12791
- const text = await readList(readPath).catch(
12792
- (error) => depth > 0 && !isMissing(error) ? true : null
12793
- );
12794
- if (text === null) return false;
12795
- if (text === true || depth >= MAX_PLAYLIST_DEPTH) return true;
12796
- if (walk.seen.has(path)) return false;
12797
- walk.seen.add(path);
12798
- for (const entry of playlistEntries(text) ?? []) {
12799
- if (await entryLeaves(entry, dirname5(path), walk, depth)) return true;
12978
+ if (probeDir) rmSync2(probeDir, { recursive: true, force: true });
12800
12979
  }
12801
- return false;
12802
12980
  }
12803
- async function entryLeaves(entry, base, walk, depth) {
12804
- if (entryLeavesFolder(entry, base, walk.folder)) return true;
12805
- if (HTTP_URL.test(entry)) return false;
12806
- for (const local of /* @__PURE__ */ new Set([entry, percentDecoded(entry)])) {
12807
- const nested = resolve2(base, local);
12808
- let verdict = walk.verdicts.get(nested);
12809
- if (verdict === void 0) {
12810
- verdict = await listLeaves(nested, nested, walk, depth + 1);
12811
- walk.verdicts.set(nested, verdict);
12812
- }
12813
- if (verdict) return true;
12814
- }
12815
- return false;
12981
+ function inputAlphaOpaqueWarning(src) {
12982
+ return `[hyperframes:render] WARNING: video src="${src}" declares an alpha channel but its first frames decode fully opaque. If it should be transparent, re-export it with an alpha pixel format and avoid remuxing afterward, which can drop the alpha while keeping the tag.
12983
+ `;
12816
12984
  }
12817
12985
 
12818
12986
  // ../engine/src/utils/urlDownloader.ts
@@ -12829,7 +12997,7 @@ import {
12829
12997
  readdirSync as readdirSync4,
12830
12998
  rmdirSync,
12831
12999
  rmSync as rmSync3,
12832
- statSync as statSync5,
13000
+ statSync as statSync4,
12833
13001
  statfsSync,
12834
13002
  unlinkSync
12835
13003
  } from "fs";
@@ -13139,10 +13307,11 @@ var capturePolicyLookup = (hostname, options, callback) => {
13139
13307
  );
13140
13308
  };
13141
13309
  var undiciTransports = /* @__PURE__ */ new Map();
13310
+ var importUndiciPackageEvenUnderBun = () => import("undici/index.js");
13142
13311
  function undiciTransport(lookup) {
13143
13312
  let transport = undiciTransports.get(lookup);
13144
13313
  if (!transport) {
13145
- transport = import("undici").then(({ Agent, fetch: undiciFetch }) => {
13314
+ transport = importUndiciPackageEvenUnderBun().then(({ Agent, fetch: undiciFetch }) => {
13146
13315
  const dispatcher = new Agent({ connect: { lookup } });
13147
13316
  return (target, options) => undiciFetch(target, { ...options, dispatcher });
13148
13317
  });
@@ -13432,7 +13601,7 @@ var DiskHeadroomGuard = class {
13432
13601
  device = 0;
13433
13602
  claim(declaredBytes) {
13434
13603
  if (this.minFreeBytes === 0) return true;
13435
- this.device = statSync5(this.dir).dev;
13604
+ this.device = statSync4(this.dir).dev;
13436
13605
  this.adjustUnreceived(declaredBytes);
13437
13606
  return this.keepsMinimum();
13438
13607
  }
@@ -13639,7 +13808,7 @@ async function fetchToPartial(url, partialPath, controller, options, onBodyBytes
13639
13808
  const readableStream = Readable.fromWeb(response.body);
13640
13809
  const fileStream = createWriteStream(partialPath, { flags: "wx" });
13641
13810
  await pipeline(readableStream, inspector, fileStream, { signal: controller.signal });
13642
- const localSize = statSync5(partialPath).size;
13811
+ const localSize = statSync4(partialPath).size;
13643
13812
  const sha256Bytes = sha256.digest();
13644
13813
  const localSha256 = sha256Bytes.toString("hex");
13645
13814
  const md5Base64 = md5.digest("base64");
@@ -14144,7 +14313,7 @@ function truncateUtf8(text, maxBytes) {
14144
14313
  }
14145
14314
 
14146
14315
  // ../engine/src/services/extractionCache.ts
14147
- import { createHash as createHash4, randomUUID as randomUUID3 } from "crypto";
14316
+ import { createHash as createHash4 } from "crypto";
14148
14317
  import {
14149
14318
  chmodSync,
14150
14319
  createReadStream as createReadStream3,
@@ -14153,11 +14322,11 @@ import {
14153
14322
  mkdirSync as mkdirSync5,
14154
14323
  readdirSync as readdirSync5,
14155
14324
  rmSync as rmSync4,
14156
- statSync as statSync6,
14325
+ statSync as statSync5,
14157
14326
  utimesSync,
14158
14327
  writeFileSync as writeFileSync3
14159
14328
  } from "fs";
14160
- import { join as join12 } from "path";
14329
+ import { basename as basename2, dirname as dirname7, join as join12 } from "path";
14161
14330
  var COMPLETE_SENTINEL = ".hf-complete";
14162
14331
  var GC_MARKER = ".hf-last-gc";
14163
14332
  function privateCacheRoot(root, uid = process.getuid?.()) {
@@ -14181,7 +14350,7 @@ async function readContentSha256(path, signal) {
14181
14350
  }
14182
14351
  function readKeyStat(videoPath) {
14183
14352
  try {
14184
- const stat = statSync6(videoPath);
14353
+ const stat = statSync5(videoPath);
14185
14354
  return { mtimeMs: Math.floor(stat.mtimeMs), size: stat.size };
14186
14355
  } catch {
14187
14356
  return null;
@@ -14220,8 +14389,15 @@ function lookupCacheEntry(rootDir, input) {
14220
14389
  const complete = existsSync10(join12(dir, COMPLETE_SENTINEL)) && hasFrameFiles(dir);
14221
14390
  return { entry: { dir, keyHash }, hit: complete };
14222
14391
  }
14223
- function partialCacheEntryDir(entry) {
14224
- return `${entry.dir}.partial-${process.pid}-${randomUUID3().slice(0, 8)}`;
14392
+ function createPartialCacheEntryDir(entry) {
14393
+ return createPartialDir(dirname7(entry.dir), basename2(entry.dir));
14394
+ }
14395
+ function createPartialDir(parent, name) {
14396
+ mkdirSync5(parent, { recursive: true });
14397
+ return createStagingDir(parent, `${name}.partial-${process.pid}-`);
14398
+ }
14399
+ function frameFileCount(dir) {
14400
+ return readdirSync5(dir).filter((file) => file.startsWith(FRAME_FILENAME_PREFIX)).length;
14225
14401
  }
14226
14402
  function isTargetExistsRenameError(err) {
14227
14403
  const code = err.code;
@@ -14232,8 +14408,9 @@ function adoptPublishedWinner(entry, partialDir) {
14232
14408
  removeDir(partialDir);
14233
14409
  return { dir: entry.dir, published: true };
14234
14410
  }
14235
- function publishCacheEntry(entry, partialDir) {
14411
+ function publishCacheEntry(entry, partialDir, expectedFrames) {
14236
14412
  try {
14413
+ if (frameFileCount(partialDir) !== expectedFrames) return { dir: partialDir, published: false };
14237
14414
  writeFileSync3(join12(partialDir, COMPLETE_SENTINEL), "", "utf-8");
14238
14415
  } catch {
14239
14416
  return { dir: partialDir, published: false };
@@ -14315,7 +14492,7 @@ function removeDir(path) {
14315
14492
  }
14316
14493
  function collectGcEntry(dir, name, now, minAgeMs, stats, remove) {
14317
14494
  try {
14318
- const dirStat = statSync6(dir);
14495
+ const dirStat = statSync5(dir);
14319
14496
  if (isPartialChild(name) && now - dirStat.mtimeMs >= minAgeMs) {
14320
14497
  remove(dir);
14321
14498
  stats.agedPartialsRemoved += 1;
@@ -14323,7 +14500,7 @@ function collectGcEntry(dir, name, now, minAgeMs, stats, remove) {
14323
14500
  }
14324
14501
  let lastUseMs = dirStat.mtimeMs;
14325
14502
  try {
14326
- lastUseMs = statSync6(join12(dir, COMPLETE_SENTINEL)).mtimeMs;
14503
+ lastUseMs = statSync5(join12(dir, COMPLETE_SENTINEL)).mtimeMs;
14327
14504
  } catch {
14328
14505
  }
14329
14506
  return { dir, size: directorySizeBytes(dir), lastUseMs, ageMs: now - lastUseMs };
@@ -14333,7 +14510,7 @@ function collectGcEntry(dir, name, now, minAgeMs, stats, remove) {
14333
14510
  }
14334
14511
  function gcSweepDue(rootDir, maxAgeMs) {
14335
14512
  try {
14336
- return Date.now() - statSync6(join12(rootDir, GC_MARKER)).mtimeMs > maxAgeMs;
14513
+ return Date.now() - statSync5(join12(rootDir, GC_MARKER)).mtimeMs > maxAgeMs;
14337
14514
  } catch {
14338
14515
  return true;
14339
14516
  }
@@ -14503,13 +14680,13 @@ function videoExtractionSourceLabel(src, baseDir) {
14503
14680
  if (/^(data|blob):/i.test(src)) return "inline video";
14504
14681
  if (URL_SCHEME.test(src)) {
14505
14682
  try {
14506
- return basename2(decodeURIComponent(new URL(src).pathname)) || "remote video";
14683
+ return basename3(decodeURIComponent(new URL(src).pathname)) || "remote video";
14507
14684
  } catch {
14508
14685
  return "remote video";
14509
14686
  }
14510
14687
  }
14511
14688
  const path = src.split(/[?#]/)[0];
14512
- const lib = WINDOWS_ABSOLUTE.test(path) ? win32 : { isAbsolute: isAbsolute2, relative: relative2, basename: basename2, normalize };
14689
+ const lib = WINDOWS_ABSOLUTE.test(path) ? win32 : { isAbsolute: isAbsolute2, relative: relative2, basename: basename3, normalize };
14513
14690
  const relativePath = lib.isAbsolute(path) ? lib.relative(baseDir, path) : lib.normalize(path);
14514
14691
  const label = relativePath.startsWith("..") || lib.isAbsolute(relativePath) ? lib.basename(path) : relativePath;
14515
14692
  return label.replace(/\\/g, "/");
@@ -15246,7 +15423,7 @@ async function extractVideoFramesRangeUnredacted(videoPath, videoId, startTime,
15246
15423
  const diagnostic = `${hdrPrefix}FFmpeg exited with code ${processResult.exitCode}${timeoutSuffix}: ` + processResult.stderr.slice(-500);
15247
15424
  const ffmpegReason = ffmpegReasonFrom(processResult.stderr, [
15248
15425
  videoPath,
15249
- basename2(videoPath),
15426
+ basename3(videoPath),
15250
15427
  videoOutputDir
15251
15428
  ]);
15252
15429
  if (timedOut) {
@@ -15647,8 +15824,6 @@ function planSupersetGroups(misses, fps) {
15647
15824
  }
15648
15825
  function sliceSupersetMember(member, superset, outputDir, fps, configuredFps) {
15649
15826
  const { work } = member.miss;
15650
- rmSync5(outputDir, { recursive: true, force: true });
15651
- mkdirSync6(outputDir, { recursive: true });
15652
15827
  const requestedFrames = extractionFrameCountForDuration(
15653
15828
  work.videoDuration,
15654
15829
  configuredFps,
@@ -15661,7 +15836,11 @@ function sliceSupersetMember(member, superset, outputDir, fps, configuredFps) {
15661
15836
  if (!sourceFrame) throw new Error(`superset frame ${member.offsetFrames + i} missing`);
15662
15837
  linkOrCopyFrame(sourceFrame, join13(outputDir, frameFileName(i + 1, work.format)));
15663
15838
  }
15664
- return extractedFramesFromDirectory(work, outputDir, work.videoPath, fps);
15839
+ const sliced = extractedFramesFromDirectory(work, outputDir, work.videoPath, fps);
15840
+ if (sliced.totalFrames !== frameCount) {
15841
+ throw new Error(`superset slice holds ${sliced.totalFrames} frames, not ${frameCount}`);
15842
+ }
15843
+ return sliced;
15665
15844
  }
15666
15845
  async function extractAllVideoFrames(videos, baseDir, options, signal, config, compiledDir) {
15667
15846
  if (options.timelineEnd !== void 0 && !Number.isFinite(options.timelineEnd)) {
@@ -15715,12 +15894,13 @@ async function extractAllVideoFrames(videos, baseDir, options, signal, config, c
15715
15894
  continue;
15716
15895
  }
15717
15896
  const roots = options.assetRoots;
15718
- if (!isHttpUrl(videoPath) && roots && !isInsideAssetRoots(videoPath, roots)) {
15897
+ const refusal = !isHttpUrl(videoPath) && roots ? assetRootsRefusal(videoPath, roots) : null;
15898
+ if (refusal) {
15719
15899
  errors.push({
15720
15900
  videoId: video.id,
15721
15901
  kind: "source_missing",
15722
15902
  retryable: false,
15723
- error: `Video source is outside the project folder: ${video.src}`
15903
+ error: `Video source is ${refusal}: ${video.src}`
15724
15904
  });
15725
15905
  continue;
15726
15906
  }
@@ -15998,9 +16178,7 @@ async function extractAllVideoFrames(videos, baseDir, options, signal, config, c
15998
16178
  );
15999
16179
  return attempted2.result;
16000
16180
  }
16001
- const partialDir = partialCacheEntryDir(cacheTarget.entry);
16002
- rmSync5(partialDir, { recursive: true, force: true });
16003
- mkdirSync6(partialDir, { recursive: true });
16181
+ let partialDir = createPartialCacheEntryDir(cacheTarget.entry);
16004
16182
  const attempted = await runVideoExtractionWithRetry(
16005
16183
  () => extractVideoFramesRange(
16006
16184
  work.videoPath,
@@ -16018,12 +16196,12 @@ async function extractAllVideoFrames(videos, baseDir, options, signal, config, c
16018
16196
  onRetry: () => {
16019
16197
  recordTransientRetries(1);
16020
16198
  rmSync5(partialDir, { recursive: true, force: true });
16021
- mkdirSync6(partialDir, { recursive: true });
16199
+ partialDir = createPartialCacheEntryDir(cacheTarget.entry);
16022
16200
  }
16023
16201
  }
16024
16202
  );
16025
16203
  const result = attempted.result;
16026
- const published = publishCacheEntry(cacheTarget.entry, partialDir);
16204
+ const published = publishCacheEntry(cacheTarget.entry, partialDir, result.totalFrames);
16027
16205
  if (!published.published) {
16028
16206
  breakdown.cachePublishFailures += 1;
16029
16207
  return { ...result, ownedByLookup: false };
@@ -16115,17 +16293,14 @@ async function extractAllVideoFrames(videos, baseDir, options, signal, config, c
16115
16293
  const { miss } = member;
16116
16294
  const { work, cacheTarget } = miss;
16117
16295
  if (!cacheTarget) {
16118
- return sliceSupersetMember(
16119
- member,
16120
- superset,
16121
- join13(options.outputDir, mediaIdPathSegment(work.video.id)),
16122
- fps,
16123
- configuredFps
16124
- );
16296
+ const outputDir = join13(options.outputDir, mediaIdPathSegment(work.video.id));
16297
+ rmSync5(outputDir, { recursive: true, force: true });
16298
+ mkdirSync6(outputDir, { recursive: true });
16299
+ return sliceSupersetMember(member, superset, outputDir, fps, configuredFps);
16125
16300
  }
16126
- const partialDir = partialCacheEntryDir(cacheTarget.entry);
16301
+ const partialDir = createPartialCacheEntryDir(cacheTarget.entry);
16127
16302
  const sliced = sliceSupersetMember(member, superset, partialDir, fps, configuredFps);
16128
- const published = publishCacheEntry(cacheTarget.entry, partialDir);
16303
+ const published = publishCacheEntry(cacheTarget.entry, partialDir, sliced.totalFrames);
16129
16304
  if (!published.published) {
16130
16305
  breakdown.cachePublishFailures += 1;
16131
16306
  return { ...sliced, ownedByLookup: false };
@@ -16135,9 +16310,9 @@ async function extractAllVideoFrames(videos, baseDir, options, signal, config, c
16135
16310
  async function executeSupersetGroup(group) {
16136
16311
  const first = group.members[0]?.miss.work;
16137
16312
  if (!first) return [];
16138
- const tempDir = cacheRootDir ? join13(cacheRootDir, `${group.groupId}.partial-${process.pid}`) : join13(options.outputDir, group.groupId);
16313
+ let tempDir;
16139
16314
  try {
16140
- rmSync5(tempDir, { recursive: true, force: true });
16315
+ tempDir = createPartialDir(cacheRootDir ?? options.outputDir, group.groupId);
16141
16316
  const superset = await extractVideoFramesRange(
16142
16317
  first.videoPath,
16143
16318
  group.groupId,
@@ -16170,7 +16345,7 @@ async function extractAllVideoFrames(videos, baseDir, options, signal, config, c
16170
16345
  );
16171
16346
  return fallback;
16172
16347
  } finally {
16173
- rmSync5(tempDir, { recursive: true, force: true });
16348
+ if (tempDir) rmSync5(tempDir, { recursive: true, force: true });
16174
16349
  }
16175
16350
  }
16176
16351
  const preparedExtractions = await Promise.all(
@@ -17026,7 +17201,7 @@ async function queryElementStacking(page, nativeHdrIds) {
17026
17201
 
17027
17202
  // ../engine/src/services/audioMixer.ts
17028
17203
  import { closeSync as closeSync4, existsSync as existsSync13, mkdirSync as mkdirSync7, openSync as openSync4, rmSync as rmSync7, writeFileSync as writeFileSync7 } from "fs";
17029
- import { join as join17, dirname as dirname9, isAbsolute as isAbsolute3, relative as relative3 } from "path";
17204
+ import { join as join17, dirname as dirname10, isAbsolute as isAbsolute3, relative as relative3 } from "path";
17030
17205
 
17031
17206
  // ../core/dist/audioFade.js
17032
17207
  var HF_AUDIO_FADE_IN_ATTR = "data-fade-in";
@@ -17063,7 +17238,7 @@ function clampFadesToDuration(fades, duration) {
17063
17238
  // ../engine/src/services/aacEncode.ts
17064
17239
  import { execFile as execFile3 } from "child_process";
17065
17240
  import { readFileSync as readFileSync6, writeFileSync as writeFileSync4 } from "fs";
17066
- import { dirname as dirname7, join as join14 } from "path";
17241
+ import { dirname as dirname8, join as join14 } from "path";
17067
17242
  var SAMPLE_RATE = 48e3;
17068
17243
  var FRAME_SAMPLES = 1024;
17069
17244
  var MIN_SEGMENT_SECONDS = 60;
@@ -17131,7 +17306,7 @@ async function encodeAac(input, outputPath, totalDuration, {
17131
17306
  if (!await supportsSettsDuration()) {
17132
17307
  return encodeInOnePass(input, outputPath, { signal, timeout, filter });
17133
17308
  }
17134
- const dir = createStagingDir(dirname7(outputPath), ".aac-segments-");
17309
+ const dir = createStagingDir(dirname8(outputPath), ".aac-segments-");
17135
17310
  try {
17136
17311
  const segments = planSegments(totalDuration, count).map((segment, k) => ({
17137
17312
  ...segment,
@@ -17297,7 +17472,7 @@ function audioFailureDiagnostics(values) {
17297
17472
 
17298
17473
  // ../engine/src/services/audioVolumeEnvelope.ts
17299
17474
  import { readFileSync as readFileSync7, rmSync as rmSync6, writeFileSync as writeFileSync5 } from "fs";
17300
- import { dirname as dirname8, join as join15 } from "path";
17475
+ import { dirname as dirname9, join as join15 } from "path";
17301
17476
 
17302
17477
  // ../core/dist/runtime/mediaVolumeEnvelope.js
17303
17478
  function normaliseEnvelope(keyframes, trackStart, baseVolume) {
@@ -17423,7 +17598,7 @@ function applyVolumeEnvelopeToWav(wavPath, keyframes, trackStart, baseVolume) {
17423
17598
  const layout = parseWavLayout(buffer);
17424
17599
  if (!layout) return false;
17425
17600
  scaleSamples(buffer, layout, gainAt);
17426
- stagingDir = createStagingDir(dirname8(wavPath), ".hf-volume-");
17601
+ stagingDir = createStagingDir(dirname9(wavPath), ".hf-volume-");
17427
17602
  const tempPath = join15(stagingDir, "audio.wav");
17428
17603
  writeFileSync5(tempPath, buffer, { flag: "wx" });
17429
17604
  renameWithRetry(tempPath, wavPath);
@@ -17658,7 +17833,7 @@ import {
17658
17833
  openSync as openSync3,
17659
17834
  readFileSync as readFileSync8,
17660
17835
  readSync,
17661
- statSync as statSync7,
17836
+ statSync as statSync6,
17662
17837
  writeFileSync as writeFileSync6,
17663
17838
  writeSync as writeSync2
17664
17839
  } from "fs";
@@ -17743,7 +17918,7 @@ function readWavHeader(path) {
17743
17918
  if (buf.length < 44 || buf.toString("ascii", 0, 4) !== "RIFF") return null;
17744
17919
  const { format, channels, sampleRate, bits, dataBody, dataSize } = readWavChunks(buf);
17745
17920
  if (dataBody === void 0 || dataSize === void 0) return null;
17746
- const dataBytes = resolveDataBytes(dataSize, statSync7(path).size - dataBody);
17921
+ const dataBytes = resolveDataBytes(dataSize, statSync6(path).size - dataBody);
17747
17922
  return {
17748
17923
  format,
17749
17924
  channels,
@@ -17905,7 +18080,9 @@ function chainPrerollSeconds(chain, limits, trackId) {
17905
18080
  );
17906
18081
  if (capped) {
17907
18082
  console.warn(
17908
- `Audio FX for track ${trackId}: the chain remembers longer than the ${limits.maxPrerollSeconds}s pre-roll cap, so its oldest repeats are cut at window seams`
18083
+ terminalText(
18084
+ `Audio FX for track ${trackId}: the chain remembers longer than the ${limits.maxPrerollSeconds}s pre-roll cap, so its oldest repeats are cut at window seams`
18085
+ )
17909
18086
  );
17910
18087
  }
17911
18088
  return seconds;
@@ -17983,7 +18160,7 @@ async function applyAudioFxChain(inputWav, chain, outputWav, options) {
17983
18160
  )
17984
18161
  }));
17985
18162
  }
17986
- if (statSync7(inputWav).size > MAX_WHOLE_FILE_BYTES) {
18163
+ if (statSync6(inputWav).size > MAX_WHOLE_FILE_BYTES) {
17987
18164
  const why = options.automation ? "parameter automation is not supported on inputs over 2 GiB" : "the WAV header of an input over 2 GiB could not be read";
17988
18165
  throw new AudioFxRenderError(`Audio FX for track ${options.trackId}: ${why} (${inputWav})`);
17989
18166
  }
@@ -18499,7 +18676,7 @@ var FAIL_ON_READ_ERROR_INSTEAD_OF_ENDING_THERE = ["-xerror"];
18499
18676
  var SIDECAR_WARM_UP_SECONDS = 1;
18500
18677
  async function extractAudioSegment(srcPath, outputPath, stage, mediaStart, duration, playbackRate = 1, signal, config, audioSidecarUrl, options) {
18501
18678
  const ffmpegProcessTimeout = config?.ffmpegProcessTimeout ?? DEFAULT_CONFIG.ffmpegProcessTimeout;
18502
- const outputDir = dirname9(outputPath);
18679
+ const outputDir = dirname10(outputPath);
18503
18680
  if (!existsSync13(outputDir)) mkdirSync7(outputDir, { recursive: true });
18504
18681
  const normalizedPlaybackRate = normalizeRateSpec(playbackRate);
18505
18682
  const sourceDuration = sourceTimeAt(normalizedPlaybackRate, duration);
@@ -18645,7 +18822,7 @@ function isRemoteElement(element, baseDir, compiledDir, config) {
18645
18822
  }
18646
18823
  async function generateSilence(outputPath, duration, signal, config) {
18647
18824
  const ffmpegProcessTimeout = config?.ffmpegProcessTimeout ?? DEFAULT_CONFIG.ffmpegProcessTimeout;
18648
- const outputDir = dirname9(outputPath);
18825
+ const outputDir = dirname10(outputPath);
18649
18826
  if (!existsSync13(outputDir)) mkdirSync7(outputDir, { recursive: true });
18650
18827
  const args = [
18651
18828
  "-f",
@@ -18699,7 +18876,7 @@ async function mixAudioTracksFlat(tracks, outputPath, totalDuration, signal, con
18699
18876
  failures: result2.failure ? [result2.failure] : void 0
18700
18877
  };
18701
18878
  }
18702
- const outputDir = dirname9(outputPath);
18879
+ const outputDir = dirname10(outputPath);
18703
18880
  if (!existsSync13(outputDir)) mkdirSync7(outputDir, { recursive: true });
18704
18881
  const buildFilterComplex = (ignoreAutomation, useNormalize2) => {
18705
18882
  const filterParts = [];
@@ -18808,7 +18985,7 @@ function groupNormalizeOptionUnsupported(stderr) {
18808
18985
  }
18809
18986
  async function mixGroupMembersFlat(memberTracks, outputPath, totalDuration, signal, config) {
18810
18987
  const ffmpegProcessTimeout = config?.ffmpegProcessTimeout ?? DEFAULT_CONFIG.ffmpegProcessTimeout;
18811
- const outputDir = dirname9(outputPath);
18988
+ const outputDir = dirname10(outputPath);
18812
18989
  if (!existsSync13(outputDir)) mkdirSync7(outputDir, { recursive: true });
18813
18990
  const buildInputFilters = (ignoreKeyframes, padMembers) => memberTracks.map((track, i) => {
18814
18991
  const volumeFilter = buildVolumeExpression(track, ignoreKeyframes);
@@ -18941,8 +19118,8 @@ async function mixGroupMembers(memberTracks, outputPath, totalDuration, signal,
18941
19118
  if (memberTracks.length <= MAX_MIX_INPUTS) {
18942
19119
  return mixGroupMembersFlat(memberTracks, outputPath, totalDuration, signal, config);
18943
19120
  }
18944
- mkdirSync7(dirname9(outputPath), { recursive: true });
18945
- const scratchDir = createStagingDir(dirname9(outputPath), ".mix-batches-");
19121
+ mkdirSync7(dirname10(outputPath), { recursive: true });
19122
+ const scratchDir = createStagingDir(dirname10(outputPath), ".mix-batches-");
18946
19123
  try {
18947
19124
  const summed = await sumInSlices(memberTracks, scratchDir, totalDuration, signal, config);
18948
19125
  if (!summed.success) return summed;
@@ -18956,8 +19133,8 @@ async function mixAudioTracks(tracks, outputPath, totalDuration, signal, config)
18956
19133
  if (tracks.length <= MAX_MIX_INPUTS) {
18957
19134
  return mixAudioTracksFlat(tracks, outputPath, totalDuration, signal, config);
18958
19135
  }
18959
- mkdirSync7(dirname9(outputPath), { recursive: true });
18960
- const scratchDir = createStagingDir(dirname9(outputPath), ".mix-batches-");
19136
+ mkdirSync7(dirname10(outputPath), { recursive: true });
19137
+ const scratchDir = createStagingDir(dirname10(outputPath), ".mix-batches-");
18961
19138
  try {
18962
19139
  const summed = await sumInSlices(tracks, scratchDir, totalDuration, signal, config);
18963
19140
  if (!summed.success) {
@@ -19068,18 +19245,19 @@ async function processCompositionAudio(elements, baseDir, workDir, outputPath, t
19068
19245
  audioSidecarUrl = config?.audioSidecarUrlByLocalPath?.get(srcPath);
19069
19246
  srcPath = remoteUrl;
19070
19247
  readInPlace = true;
19071
- } else if (config?.assetRoots && !isInsideAssetRoots(srcPath, config.assetRoots)) {
19072
- failures.push({
19073
- stage: "source",
19074
- reason: "source_not_found",
19075
- owner: "user",
19076
- retryable: false,
19077
- elementId: element.id,
19078
- detail: boundedDetail(
19079
- `Audio element ${element.id} source is outside the project folder`
19080
- )
19081
- });
19082
- return;
19248
+ } else {
19249
+ const refusal = config?.assetRoots ? assetRootsRefusal(srcPath, config.assetRoots) : null;
19250
+ if (refusal) {
19251
+ failures.push({
19252
+ stage: "source",
19253
+ reason: "source_not_found",
19254
+ owner: "user",
19255
+ retryable: false,
19256
+ elementId: element.id,
19257
+ detail: boundedDetail(`Audio element ${element.id} source is ${refusal}`)
19258
+ });
19259
+ return;
19260
+ }
19083
19261
  }
19084
19262
  }
19085
19263
  if (isHttpUrl(srcPath) && !readInPlace) {
@@ -19127,7 +19305,9 @@ async function processCompositionAudio(elements, baseDir, workDir, outputPath, t
19127
19305
  }
19128
19306
  if (element.end - element.start <= 0) {
19129
19307
  console.warn(
19130
- `[audioMixer] ${element.id} has no data-duration or data-end; its length is unknown, so it plays to the end of its source`
19308
+ terminalText(
19309
+ `[audioMixer] ${element.id} has no data-duration or data-end; its length is unknown, so it plays to the end of its source`
19310
+ )
19131
19311
  );
19132
19312
  let metadata;
19133
19313
  try {
@@ -20252,7 +20432,7 @@ function getSystemResources() {
20252
20432
  // ../engine/src/services/fileServer.ts
20253
20433
  import { Hono } from "hono";
20254
20434
  import { serve } from "@hono/node-server";
20255
- import { readFileSync as readFileSync9, openSync as openSync5, fstatSync, closeSync as closeSync5, statSync as statSync8, constants as constants2 } from "fs";
20435
+ import { readFileSync as readFileSync9, openSync as openSync5, fstatSync, closeSync as closeSync5, statSync as statSync7, constants as constants2 } from "fs";
20256
20436
  import { join as join20, extname as extname3 } from "path";
20257
20437
  import { hostname as machineName, networkInterfaces } from "os";
20258
20438
 
@@ -20311,7 +20491,7 @@ function readRegularFile(filePath) {
20311
20491
  } catch (error) {
20312
20492
  if (error instanceof Error && "code" in error && (error.code === "ENOENT" || error.code === "ENOTDIR"))
20313
20493
  return null;
20314
- if (!statSync8(filePath, { throwIfNoEntry: false })?.isFile()) return null;
20494
+ if (!statSync7(filePath, { throwIfNoEntry: false })?.isFile()) return null;
20315
20495
  throw error;
20316
20496
  }
20317
20497
  try {
@@ -20700,7 +20880,7 @@ async function launchHdrBrowser(width, height) {
20700
20880
  const chromePath = resolveFullChromePath();
20701
20881
  if (!chromePath) {
20702
20882
  throw new Error(
20703
- "[HDR] No Chrome binary found. Install: npx @puppeteer/browsers install chrome@stable"
20883
+ "[HDR] Name a full Chrome in HYPERFRAMES_BROWSER_PATH: HDR capture does not start a cached browser."
20704
20884
  );
20705
20885
  }
20706
20886
  const browser = await ppt.launch({
@@ -20816,6 +20996,14 @@ export {
20816
20996
  getFfmpegBinary,
20817
20997
  getFfprobeBinary,
20818
20998
  assertConfiguredFfmpegBinariesExist,
20999
+ urlInputArgs,
21000
+ NOT_MEDIA_PAYLOAD,
21001
+ NotMediaPayloadError,
21002
+ fingerprintElementId,
21003
+ isNotMediaPayload,
21004
+ assertMediaPayload,
21005
+ isNotImagePayload,
21006
+ playlistLeavesItsFolder,
20819
21007
  trackChildProcess,
20820
21008
  killTrackedProcesses,
20821
21009
  ManagedChildProcess,
@@ -20924,12 +21112,8 @@ export {
20924
21112
  HF_AUDIO_GROUP_ATTR,
20925
21113
  isSelfOrAncestorHidden,
20926
21114
  isInsideAssetRoots,
20927
- NOT_MEDIA_PAYLOAD,
20928
- NotMediaPayloadError,
20929
- fingerprintElementId,
20930
- isNotMediaPayload,
20931
- assertMediaPayload,
20932
- playlistLeavesItsFolder,
21115
+ isPrivateUnderAssetRoots,
21116
+ assetRootsRefusal,
20933
21117
  safeDownloadUrlIdentity,
20934
21118
  writeUrlDownloadTelemetry,
20935
21119
  isUrlNotPermittedError,