@aussieljk/forkbook 0.0.1-2 → 0.0.1-21

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 (536) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +35 -53
  3. package/assets/addon-vitest/templates/vitest.config.4.template.ts +2 -2
  4. package/assets/browser/favicon-wrapper.svg +4 -4
  5. package/assets/browser/favicon.svg +1 -1
  6. package/assets/browser/inter-LICENSE.txt +92 -0
  7. package/assets/browser/inter-variable-italic.woff2 +0 -0
  8. package/assets/browser/inter-variable.woff2 +0 -0
  9. package/assets/browser/mirror-ball.png +0 -0
  10. package/assets/builder-vite/iframe.html +8 -24
  11. package/assets/create/rendererAssets/common/Configure.mdx +100 -100
  12. package/assets/create/rendererAssets/common/button.css +7 -7
  13. package/assets/create/rendererAssets/common/header.css +6 -6
  14. package/assets/create/rendererAssets/common/page.css +12 -12
  15. package/assets/create/templates/react-native/index.expo.js +4 -4
  16. package/assets/create/templates/react-native/index.js +5 -5
  17. package/assets/server/base-preview-body.html +32 -32
  18. package/assets/server/base-preview-head.html +86 -86
  19. package/assets/server/template.ejs +31 -26
  20. package/dist/_browser-chunks/{Color-PCLE2J36.js → Color-7FO5YFB5.js} +8 -8
  21. package/dist/_browser-chunks/{DocsRenderer-JXND3PVQ.js → DocsRenderer-DKXSW2OY.js} +2 -2
  22. package/dist/_browser-chunks/WithTooltip-QWFSUQZP.js +199 -0
  23. package/dist/_browser-chunks/{chunk-RBCHTR7C.js → chunk-2ELGJRFZ.js} +1 -1
  24. package/dist/_browser-chunks/{chunk-PFRNG3UC.js → chunk-2WZWS7GJ.js} +5 -5
  25. package/dist/_browser-chunks/{chunk-52CW7FF7.js → chunk-3QNZOMD7.js} +8 -3
  26. package/dist/_browser-chunks/{chunk-LV5PIKV4.js → chunk-3QPZOXB7.js} +6 -8
  27. package/dist/_browser-chunks/{chunk-ODVJ3XZJ.js → chunk-4BOJAE7P.js} +14 -10
  28. package/dist/_browser-chunks/{chunk-2MEPHP35.js → chunk-4KIQBRD2.js} +1 -1
  29. package/dist/_browser-chunks/{chunk-KQ7CRO2B.js → chunk-5Z3MWCFR.js} +12 -12
  30. package/dist/_browser-chunks/chunk-6AKCRYVX.js +6 -0
  31. package/dist/_browser-chunks/{chunk-W5M6NPS3.js → chunk-6SL45YM3.js} +15 -18
  32. package/dist/_browser-chunks/{chunk-2SCZVUKW.js → chunk-AN2LJG5I.js} +1 -1
  33. package/dist/_browser-chunks/{chunk-P6PK47TQ.js → chunk-BLCZ3C5M.js} +48 -83
  34. package/dist/_browser-chunks/{chunk-RSPAQWVJ.js → chunk-BNP234B4.js} +1 -1
  35. package/dist/_browser-chunks/{chunk-JYVGARBG.js → chunk-BSYOFSF6.js} +770 -720
  36. package/dist/_browser-chunks/{chunk-JSBKXXXF.js → chunk-DHTLVXAL.js} +38 -45
  37. package/dist/_browser-chunks/{chunk-GNZY6LOW.js → chunk-DISGPOF4.js} +54 -51
  38. package/dist/_browser-chunks/chunk-DNJ3OSLB.js +6021 -0
  39. package/dist/_browser-chunks/{chunk-6SXYJQST.js → chunk-E6QKKKLO.js} +21 -6
  40. package/dist/_browser-chunks/{chunk-FJGWSWL5.js → chunk-EBSOKHFG.js} +10 -4
  41. package/dist/_browser-chunks/{chunk-CFAOWGL7.js → chunk-ECMVTOVD.js} +1 -1
  42. package/dist/_browser-chunks/{chunk-CFWWCCZV.js → chunk-ENHFQXYS.js} +9 -7
  43. package/dist/_browser-chunks/{chunk-YTIT5NA5.js → chunk-EW2M3URL.js} +91 -84
  44. package/dist/_browser-chunks/chunk-FAOLWWRN.js +20 -0
  45. package/dist/_browser-chunks/{chunk-MFMDGWP6.js → chunk-FCULT3AE.js} +3 -3
  46. package/dist/_browser-chunks/{chunk-46Z7NGAS.js → chunk-HX443LKV.js} +1 -1
  47. package/dist/_browser-chunks/chunk-HZFHNYRC.js +53 -0
  48. package/dist/_browser-chunks/chunk-IFADVEQE.js +669 -0
  49. package/dist/_browser-chunks/{chunk-OQWFVDIN.js → chunk-KQJ4T6JL.js} +31 -25
  50. package/dist/_browser-chunks/{chunk-RNTIV5CE.js → chunk-LYYXDWR2.js} +9 -9
  51. package/dist/_browser-chunks/{chunk-V5M7Q4HT.js → chunk-MJIDTL3X.js} +4 -14
  52. package/dist/_browser-chunks/{chunk-V2G23FV7.js → chunk-N5WQGLI7.js} +1 -1
  53. package/dist/_browser-chunks/{chunk-EIYAKDGP.js → chunk-NA4ITZTK.js} +127 -105
  54. package/dist/_browser-chunks/{chunk-RMYQ3QN3.js → chunk-NK5SGJNG.js} +22 -17
  55. package/dist/_browser-chunks/chunk-NPNIBOPF.js +18 -0
  56. package/dist/_browser-chunks/{chunk-YEKO6BHJ.js → chunk-ONTSNQON.js} +1 -1
  57. package/dist/_browser-chunks/chunk-OOETBSA7.js +502 -0
  58. package/dist/_browser-chunks/chunk-PFYL47RM.js +45 -0
  59. package/dist/_browser-chunks/{chunk-OD6IBQCC.js → chunk-PQRPDA4U.js} +5 -5
  60. package/dist/_browser-chunks/{chunk-2JDQ35OA.js → chunk-PU7D2WDP.js} +0 -11
  61. package/dist/_browser-chunks/chunk-PZQRXPVR.js +21 -0
  62. package/dist/_browser-chunks/{chunk-5WMXI5GW.js → chunk-QFO2B4X2.js} +31 -28
  63. package/dist/_browser-chunks/{chunk-2JT76G3E.js → chunk-SBOQ4QPY.js} +15 -15
  64. package/dist/_browser-chunks/{chunk-ZTQ5MEJ5.js → chunk-UMGDO2ZM.js} +3 -37
  65. package/dist/_browser-chunks/{chunk-5I7E4GMO.js → chunk-WY2LUGOH.js} +1 -1
  66. package/dist/_browser-chunks/chunk-XKTORVEQ.js +255 -0
  67. package/dist/_browser-chunks/chunk-XSVERCGB.js +91 -0
  68. package/dist/_browser-chunks/{chunk-FVSEPWWX.js → chunk-XTQCLWVH.js} +325 -1635
  69. package/dist/_browser-chunks/{chunk-MDOL7KML.js → chunk-YJO5BK52.js} +7 -3
  70. package/dist/_browser-chunks/{chunk-66OCZ54D.js → chunk-ZF37BMDS.js} +6 -2
  71. package/dist/_browser-chunks/{chunk-C3D4HEFY.js → chunk-ZIZCGWCG.js} +348 -170
  72. package/dist/_browser-chunks/{matchers-YLBYSYAF.js → matchers-2HVLNCVO.js} +4 -4
  73. package/dist/_browser-chunks/{react-dom-client-4OHE3QDV.js → react-dom-client-SLBUX3U3.js} +1 -1
  74. package/dist/_node-chunks/{attached-runtime-I2G4WLJI.js → attached-runtime-UC2CB4GH.js} +37 -35
  75. package/dist/_node-chunks/builder-manager-S5UUKVOR.js +1174 -0
  76. package/dist/_node-chunks/{chunk-OUW6R7C3.js → chunk-3335ZZIO.js} +6 -6
  77. package/dist/_node-chunks/{chunk-V2DY426G.js → chunk-3D6N6P2R.js} +283 -306
  78. package/dist/_node-chunks/{chunk-3Y6AAY5H.js → chunk-3ER54PQM.js} +8 -8
  79. package/dist/_node-chunks/{chunk-DC7DKR5K.js → chunk-3H5C52QU.js} +6 -6
  80. package/dist/_node-chunks/chunk-3UI3TQ7R.js +28 -0
  81. package/dist/_node-chunks/{chunk-Q7QNUM5H.js → chunk-4C3ACAHV.js} +6 -6
  82. package/dist/_node-chunks/{chunk-XGIUVY52.js → chunk-4UTCKJEQ.js} +7 -7
  83. package/dist/_node-chunks/chunk-53A5CYDK.js +572 -0
  84. package/dist/_node-chunks/{chunk-4FEANXWU.js → chunk-53PSBDRK.js} +140 -118
  85. package/dist/_node-chunks/{chunk-3W7F2B7P.js → chunk-54MO4QLB.js} +6 -6
  86. package/dist/_node-chunks/{chunk-7GUDZVRQ.js → chunk-5CJMRQZ6.js} +6 -6
  87. package/dist/_node-chunks/chunk-5HOM7B4V.js +20 -0
  88. package/dist/_node-chunks/{chunk-BSKFCWQD.js → chunk-5QG6AXK4.js} +7 -7
  89. package/dist/_node-chunks/chunk-67XVZZUO.js +405 -0
  90. package/dist/_node-chunks/{chunk-EWOX7HPJ.js → chunk-6HQJJDLH.js} +6 -6
  91. package/dist/_node-chunks/chunk-6IPHWCFI.js +29 -0
  92. package/dist/_node-chunks/{chunk-NDWKJ4CL.js → chunk-6XYOFBRD.js} +98 -129
  93. package/dist/_node-chunks/{chunk-TNJIXE37.js → chunk-7IAYDGYH.js} +6 -6
  94. package/dist/_node-chunks/{chunk-ICPBH3E7.js → chunk-7P67PUU2.js} +7 -7
  95. package/dist/_node-chunks/{chunk-XLP2ZKXV.js → chunk-AAK5BBF2.js} +7 -7
  96. package/dist/_node-chunks/{chunk-CCOTJ4FC.js → chunk-BGUVBOOU.js} +10 -10
  97. package/dist/_node-chunks/chunk-BNGBOASQ.js +25 -0
  98. package/dist/_node-chunks/{chunk-VLOXOXXE.js → chunk-BWZWCVVH.js} +9 -9
  99. package/dist/_node-chunks/{chunk-SWO5CDYU.js → chunk-C6HQ6WLU.js} +8 -8
  100. package/dist/_node-chunks/chunk-CJHRH777.js +20 -0
  101. package/dist/_node-chunks/{chunk-IK4FGZLR.js → chunk-COEW4ORP.js} +6 -6
  102. package/dist/_node-chunks/{chunk-JGGFYIG5.js → chunk-CVHDAEDZ.js} +7 -7
  103. package/dist/_node-chunks/{chunk-YCMRA6RX.js → chunk-CXGOQNGI.js} +7 -7
  104. package/dist/_node-chunks/chunk-D4XTQWRM.js +11 -0
  105. package/dist/_node-chunks/{chunk-BS2WMZMR.js → chunk-D5V6CZ6U.js} +7 -7
  106. package/dist/_node-chunks/{chunk-XHL2LVBM.js → chunk-DCTXJ4TT.js} +14 -16
  107. package/dist/_node-chunks/{chunk-WCULS5TP.js → chunk-DP6WFY3D.js} +7 -7
  108. package/dist/_node-chunks/chunk-E23GDXG6.js +271 -0
  109. package/dist/_node-chunks/{chunk-GEFQN7K3.js → chunk-E3ZFMURC.js} +8 -8
  110. package/dist/_node-chunks/{chunk-WZJF2OUH.js → chunk-E6O3NA44.js} +7 -7
  111. package/dist/_node-chunks/{chunk-RWFIFGO5.js → chunk-ECS3WDOU.js} +8 -8
  112. package/dist/_node-chunks/{chunk-XI6B6P47.js → chunk-FB5YJWOH.js} +6 -6
  113. package/dist/_node-chunks/{chunk-3SDUYDXH.js → chunk-FCK5FM6D.js} +7 -7
  114. package/dist/_node-chunks/{chunk-6YKBRP72.js → chunk-FJUGPEJK.js} +6 -6
  115. package/dist/_node-chunks/{chunk-TFEWM4E3.js → chunk-FPYXI76E.js} +75 -75
  116. package/dist/_node-chunks/chunk-GEWVOY3F.js +62 -0
  117. package/dist/_node-chunks/{chunk-ET7PWEO7.js → chunk-GHZ44BFB.js} +14 -13
  118. package/dist/_node-chunks/{chunk-LXBD4UL4.js → chunk-GJMFISS3.js} +8 -8
  119. package/dist/_node-chunks/{chunk-FK7KGTV7.js → chunk-GK2Y2RFX.js} +7 -7
  120. package/dist/_node-chunks/{chunk-FPZB5OI7.js → chunk-GP6YBA2R.js} +6 -6
  121. package/dist/_node-chunks/{chunk-34EO2PUT.js → chunk-GQUFGJ4D.js} +6 -6
  122. package/dist/_node-chunks/{chunk-HMP2G23X.js → chunk-H4CRQDTK.js} +6 -6
  123. package/dist/_node-chunks/{chunk-2BUPBPFB.js → chunk-HCDG54OG.js} +7 -7
  124. package/dist/_node-chunks/{chunk-U5W53R2J.js → chunk-HGJMP4EI.js} +506 -494
  125. package/dist/_node-chunks/chunk-HSX6BDBA.js +18 -0
  126. package/dist/_node-chunks/{chunk-UMUBKI6E.js → chunk-IPFPWMT5.js} +1320 -437
  127. package/dist/_node-chunks/chunk-KRIOC4WF.js +281 -0
  128. package/dist/_node-chunks/{chunk-TINO74G5.js → chunk-KUL2MJ6N.js} +6 -6
  129. package/dist/_node-chunks/{chunk-LO56I6E2.js → chunk-LUR6QTYB.js} +10 -10
  130. package/dist/_node-chunks/{chunk-YZFWBA5L.js → chunk-LYS7TI35.js} +368 -321
  131. package/dist/_node-chunks/chunk-MDTXL6SN.js +2613 -0
  132. package/dist/_node-chunks/{chunk-LCK4ZQKG.js → chunk-MIIPXT4S.js} +9 -9
  133. package/dist/_node-chunks/chunk-MLWGAA2I.js +138 -0
  134. package/dist/_node-chunks/{chunk-42UWAGPW.js → chunk-MWUGCUB5.js} +52 -22
  135. package/dist/_node-chunks/{chunk-JDXXX6LB.js → chunk-MX5MVLEK.js} +6 -6
  136. package/dist/_node-chunks/chunk-N44UIGCO.js +47 -0
  137. package/dist/_node-chunks/{chunk-OISX4AGQ.js → chunk-NP2JHOFY.js} +37 -31
  138. package/dist/_node-chunks/chunk-OMNGOPNG.js +52 -0
  139. package/dist/_node-chunks/{chunk-ZWBCQ4MJ.js → chunk-OO2GTHUF.js} +9 -17
  140. package/dist/_node-chunks/{chunk-F3ZFKBHY.js → chunk-PC57BIYZ.js} +8 -8
  141. package/dist/_node-chunks/chunk-PHWMAF5C.js +49 -0
  142. package/dist/_node-chunks/{chunk-B5J7Q7J4.js → chunk-PLIQQETC.js} +7 -7
  143. package/dist/_node-chunks/{chunk-H32DYT6P.js → chunk-QMYCIS2U.js} +6 -6
  144. package/dist/_node-chunks/{chunk-DUR55DJJ.js → chunk-QZIDK3GX.js} +89 -71
  145. package/dist/_node-chunks/{chunk-UVINFLGY.js → chunk-ROJ6RSIJ.js} +7 -7
  146. package/dist/_node-chunks/{chunk-E6YESGLX.js → chunk-S2NB6QEG.js} +542 -1049
  147. package/dist/_node-chunks/{chunk-TWI4GVH7.js → chunk-S6VCOSQS.js} +6 -6
  148. package/dist/_node-chunks/{chunk-KISMCCP5.js → chunk-SEVOOOB2.js} +474 -479
  149. package/dist/_node-chunks/{chunk-JZOO7GGC.js → chunk-SFT6ZAVN.js} +6 -6
  150. package/dist/_node-chunks/{chunk-RRN2V55B.js → chunk-SXBUK4F6.js} +7 -7
  151. package/dist/_node-chunks/{chunk-WNZ2UMFM.js → chunk-TGF6Q66I.js} +15 -9
  152. package/dist/_node-chunks/{chunk-NIBT7XDZ.js → chunk-TGFHWGGT.js} +9 -6
  153. package/dist/_node-chunks/chunk-TTLSBLPQ.js +620 -0
  154. package/dist/_node-chunks/{chunk-SVTBJ7Q3.js → chunk-UUAEW2AR.js} +6 -6
  155. package/dist/_node-chunks/chunk-VQHM66NL.js +534 -0
  156. package/dist/_node-chunks/{chunk-H4PPVMP5.js → chunk-VSTTY3TM.js} +6 -6
  157. package/dist/_node-chunks/{chunk-2DSIDINN.js → chunk-XDBSAFUB.js} +650 -9
  158. package/dist/_node-chunks/{chunk-OWNFOGTA.js → chunk-XTQQGAUZ.js} +7 -7
  159. package/dist/_node-chunks/{chunk-CXRU72ET.js → chunk-YMJVSFJT.js} +6 -6
  160. package/dist/_node-chunks/{chunk-DHJFTB4K.js → chunk-YXEKWVJQ.js} +7 -7
  161. package/dist/_node-chunks/{chunk-SLWQNBGO.js → chunk-Z6CUUWJO.js} +34 -949
  162. package/dist/_node-chunks/{chunk-TD5PLLQG.js → chunk-ZAIGR7EV.js} +64 -17
  163. package/dist/_node-chunks/{chunk-6KEHV53S.js → chunk-ZCFXEFR6.js} +33 -41
  164. package/dist/_node-chunks/{chunk-FW2HQUBQ.js → chunk-ZHUBOYOD.js} +6 -6
  165. package/dist/_node-chunks/{chunk-MA24JW6C.js → chunk-ZHUBTBP2.js} +25 -8
  166. package/dist/_node-chunks/{chunk-RXNJDRGO.js → chunk-ZSTIFZHY.js} +21 -25
  167. package/dist/_node-chunks/dist-TRTHRODT.js +16 -0
  168. package/dist/_node-chunks/dist-XPLJ5T4W.js +27 -0
  169. package/dist/_node-chunks/{local-runtime-NTKIN2QT.js → local-runtime-AC7MOWYK.js} +21 -22
  170. package/dist/_node-chunks/{mdx-plugin-MWISDWDQ.js → mdx-plugin-ZW26VGEP.js} +2263 -130
  171. package/dist/_node-chunks/{monorepo-LIRFMQXE.js → monorepo-T2KZK62Q.js} +12 -12
  172. package/dist/_node-chunks/{monorepo-optimized-tests-relaxed-limits-no-story-deletion-CPDW4XTW.js → monorepo-optimized-tests-relaxed-limits-no-story-deletion-2CWUUF6H.js} +12 -12
  173. package/dist/_node-chunks/optimized-tests-4AK3PFSX.js +22 -0
  174. package/dist/_node-chunks/{pattern-copy-play-EKHIUAU2.js → pattern-copy-play-CMRGEXHM.js} +12 -12
  175. package/dist/_node-chunks/postinstallAddon-OUQENFYO.js +20 -0
  176. package/dist/_node-chunks/{rehype-external-links-BUN3HUCO.js → rehype-external-links-LHOAIJ2E.js} +9 -9
  177. package/dist/_node-chunks/{rehype-slug-PLADX223.js → rehype-slug-K54MMYY6.js} +9 -9
  178. package/dist/_node-chunks/{relaxed-limits-GBHW6KIQ.js → relaxed-limits-TTL4PWH7.js} +12 -12
  179. package/dist/_node-chunks/{run-NL66VTNR.js → run-6DXBB5F7.js} +294 -30
  180. package/dist/_node-chunks/{run-KDTIZNSY.js → run-BMTV5ZAO.js} +18 -18
  181. package/dist/_node-chunks/{setup-MGC7BQO6.js → setup-FDPYW25Y.js} +9 -9
  182. package/dist/_node-chunks/{vitest.config.4.template-JH2THZFG.js → vitest.config.4.template-2TCFWAAI.js} +9 -9
  183. package/dist/actions/decorator.js +18 -22
  184. package/dist/actions/index.d.ts +4 -4
  185. package/dist/actions/index.js +3 -2
  186. package/dist/addon-a11y/index.d.ts +3 -3
  187. package/dist/addon-a11y/index.js +3 -2
  188. package/dist/addon-a11y/manager.js +41 -38
  189. package/dist/addon-a11y/preset.js +7 -7
  190. package/dist/addon-a11y/preview.d.ts +8 -2
  191. package/dist/addon-a11y/preview.js +3 -2
  192. package/dist/addon-comments/manager.js +353 -0
  193. package/dist/addon-comments/preset.js +80 -0
  194. package/dist/addon-comments/preview.js +101 -0
  195. package/dist/addon-docs/blocks.d.ts +123 -85
  196. package/dist/addon-docs/blocks.js +159 -85
  197. package/dist/addon-docs/index.d.ts +21 -21
  198. package/dist/addon-docs/index.js +3 -3
  199. package/dist/addon-docs/manager.js +6 -6
  200. package/dist/addon-docs/preset.js +12 -12
  201. package/dist/addon-docs/preview.d.ts +3 -1
  202. package/dist/addon-docs/preview.js +1 -1
  203. package/dist/addon-links/index.d.ts +2 -1
  204. package/dist/addon-links/index.js +5 -2
  205. package/dist/addon-links/preview.d.ts +1 -1
  206. package/dist/addon-links/preview.js +5 -2
  207. package/dist/addon-links/react/index.js +4 -1
  208. package/dist/addon-mcp/preset.js +203 -84
  209. package/dist/addon-mcp/preview.js +1 -1
  210. package/dist/addon-mcp/tools/preview-stories/preview-stories-app-script.js +71 -71
  211. package/dist/addon-ondevice-actions/index.js +5 -1
  212. package/dist/addon-ondevice-actions/register.js +5 -1
  213. package/dist/addon-ondevice-controls/index.js +1 -1
  214. package/dist/addon-ondevice-controls/register.js +1 -1
  215. package/dist/addon-pseudo-states/index.d.ts +1 -1
  216. package/dist/addon-pseudo-states/index.js +1 -1
  217. package/dist/addon-pseudo-states/manager.js +2 -2
  218. package/dist/addon-pseudo-states/preview.d.ts +1 -1
  219. package/dist/addon-pseudo-states/preview.js +1 -1
  220. package/dist/addon-themes/index.d.ts +7 -6
  221. package/dist/addon-themes/index.js +2 -2
  222. package/dist/addon-themes/manager.js +4 -4
  223. package/dist/addon-themes/postinstall.js +7 -7
  224. package/dist/addon-themes/preview.js +2 -2
  225. package/dist/addon-vitest/constants.js +8 -8
  226. package/dist/addon-vitest/manager.js +32 -23
  227. package/dist/addon-vitest/node/coverage-reporter.js +11 -11
  228. package/dist/addon-vitest/node/vitest.js +37 -37
  229. package/dist/addon-vitest/postinstall.js +10 -10
  230. package/dist/addon-vitest/preset.js +26 -26
  231. package/dist/addon-vitest/vitest-plugin/global-setup.js +23 -23
  232. package/dist/addon-vitest/vitest-plugin/index.js +83 -73
  233. package/dist/addon-vitest/vitest-plugin/setup-file-with-project-annotations.js +3 -3
  234. package/dist/addon-vitest/vitest-plugin/setup-file.js +1 -1
  235. package/dist/babel/index.d.ts +241 -995
  236. package/dist/babel/index.js +30583 -38
  237. package/dist/backgrounds/index.d.ts +1 -1
  238. package/dist/bin/core.js +122 -110
  239. package/dist/bin/dispatcher.js +18 -16
  240. package/dist/bin/loader.js +17 -16
  241. package/dist/builder-next/index.d.ts +59 -0
  242. package/dist/builder-next/index.js +201 -0
  243. package/dist/builder-vite/index.d.ts +8 -3
  244. package/dist/builder-vite/index.js +80 -25
  245. package/dist/builder-vite/preset.js +13 -13
  246. package/dist/channels/index.d.ts +3 -2
  247. package/dist/channels/index.js +97 -24
  248. package/dist/{chunk-Dr3R0DXk.d.ts → chunk-B-NVyPqN.d.ts} +2 -2
  249. package/dist/{chunk-C2p5r3Vt.d.ts → chunk-B53gRJBs.d.ts} +838 -703
  250. package/dist/{chunk-DoIGKY33.d.ts → chunk-BLZXEm1K.d.ts} +6 -8
  251. package/dist/chunk-BcYKnZln.d.ts +10 -0
  252. package/dist/{chunk-Bpi2tz-6.d.ts → chunk-BspNQvZn.d.ts} +21 -23
  253. package/dist/{chunk-BCoJQE-f.d.ts → chunk-BtKww7r1.d.ts} +6 -4
  254. package/dist/chunk-CFhJCPSB.d.ts +48 -0
  255. package/dist/{chunk-DtHByo32.d.ts → chunk-CFk6djyM.d.ts} +5 -5
  256. package/dist/{chunk-CwQKNaYL.d.ts → chunk-CMx6bGAU.d.ts} +2 -2
  257. package/dist/{chunk-DEVFdzxR.d.ts → chunk-CRmUwbkb.d.ts} +4 -4
  258. package/dist/{chunk-CMeX4WRe.d.ts → chunk-CT2iXaHz.d.ts} +1 -1
  259. package/dist/{chunk-pcFXCimE.d.ts → chunk-CmV7WZzR.d.ts} +124 -2
  260. package/dist/{chunk-BGkgZp-H.d.ts → chunk-D3uSIa6H.d.ts} +9 -1
  261. package/dist/{chunk-DzuY9DXg.d.ts → chunk-DDd8BhTY.d.ts} +2 -2
  262. package/dist/{chunk-Dw1z1Pki.d.ts → chunk-DNCU78oW.d.ts} +160 -323
  263. package/dist/chunk-DVIvUVkS.d.ts +195 -0
  264. package/dist/{chunk-gCX81nOr.d.ts → chunk-DgzPaTw9.d.ts} +3 -3
  265. package/dist/{chunk-Kt1tW-D1.d.ts → chunk-Dm-iHJ-s.d.ts} +3 -3
  266. package/dist/{chunk-C-bavsOH.d.ts → chunk-Dw_4ad2Y.d.ts} +6 -6
  267. package/dist/chunk-Susgfkap.d.ts +20 -0
  268. package/dist/{chunk-B2t1tGRh.d.ts → chunk-bhl-7rRD.d.ts} +40 -15
  269. package/dist/{chunk-BXLImeLy.d.ts → chunk-r-Vjut9o.d.ts} +52 -11
  270. package/dist/cli/index.d.ts +15 -904
  271. package/dist/cli/index.js +49 -5209
  272. package/dist/cli/skills/content/index.d.ts +3 -3
  273. package/dist/cli/skills/content/index.js +3 -3
  274. package/dist/cli/tools/sdk/child-host.d.ts +1 -1
  275. package/dist/cli/tools/sdk/child-host.js +17 -17
  276. package/dist/cli/tools/sdk/index.d.ts +4 -4
  277. package/dist/cli/tools/sdk/index.js +18 -18
  278. package/dist/cli-commands/bin/index.js +7 -7
  279. package/dist/client-logger/index.d.ts +20 -21
  280. package/dist/client-logger/index.js +5 -2
  281. package/dist/common/index.d.ts +32 -44
  282. package/dist/common/index.js +89 -98
  283. package/dist/components/index.d.ts +86 -272
  284. package/dist/components/index.js +2759 -8547
  285. package/dist/core-events/index.d.ts +16 -7
  286. package/dist/core-events/index.js +5 -5
  287. package/dist/core-server/index.d.ts +95 -26
  288. package/dist/core-server/index.js +1675 -408
  289. package/dist/core-server/presets/common-manager.js +837 -1335
  290. package/dist/core-server/presets/common-override-preset.js +12 -10
  291. package/dist/core-server/presets/common-preset.js +100 -282
  292. package/dist/create/bin/index.js +7 -7
  293. package/dist/create/index.js +15 -15
  294. package/dist/csf/csf-utils.d.ts +1 -1
  295. package/dist/csf/index.d.ts +6 -6
  296. package/dist/csf/index.js +90 -159
  297. package/dist/csf-tools/index.d.ts +66 -54
  298. package/dist/csf-tools/index.js +19 -17
  299. package/dist/docs-tools/index.d.ts +332 -16
  300. package/dist/docs-tools/index.js +3 -3
  301. package/dist/highlight/index.d.ts +1 -1
  302. package/dist/instrumenter/index.d.ts +5 -5
  303. package/dist/instrumenter/index.js +31 -19
  304. package/dist/manager/_manager-chunks/{globals-runtime-BvM-NY2g.js → globals-runtime-B4NRbNSS.js} +638 -1731
  305. package/dist/{preview/_chunks/runtime-CqHxptiK.js → manager/_manager-chunks/globals-runtime-BC43T1rL.js} +3413 -173
  306. package/dist/manager/_manager-chunks/{globals-runtime-qKvCZHFY.js → globals-runtime-BJ6EZqH7.js} +1035 -623
  307. package/dist/manager/_manager-chunks/{globals-runtime-Rp_zjGnh.js → globals-runtime-BfXaq_CP.js} +2 -2
  308. package/dist/manager/_manager-chunks/{globals-runtime-C02fvgcd.js → globals-runtime-BkSn_Jpe.js} +411 -379
  309. package/dist/manager/_manager-chunks/{globals-runtime-eLPTIfX-.js → globals-runtime-BnQ7i5wq.js} +232 -370
  310. package/dist/manager/_manager-chunks/globals-runtime-BtduS2C2.js +10601 -0
  311. package/dist/manager/_manager-chunks/globals-runtime-BzuYs3dZ.js +1971 -0
  312. package/dist/manager/_manager-chunks/globals-runtime-CBviMKtt.js +446 -0
  313. package/dist/manager/_manager-chunks/globals-runtime-CS41oTca.js +1808 -0
  314. package/dist/manager/_manager-chunks/{globals-runtime-BmphMP6z.js → globals-runtime-Cisw9IIE.js} +11 -11
  315. package/dist/manager/_manager-chunks/globals-runtime-CoTrrHG3.js +1163 -0
  316. package/dist/manager/_manager-chunks/{globals-runtime-FC201B7s.js → globals-runtime-DCmvKMN5.js} +2 -1
  317. package/dist/manager/_manager-chunks/globals-runtime-DgO0hT2p.js +32 -0
  318. package/dist/manager/_manager-chunks/{globals-runtime-DpNYC-qi.js → globals-runtime-DpvE_zRs.js} +1013 -782
  319. package/dist/manager/_manager-chunks/globals-runtime-Me9Bl-sx.js +156 -0
  320. package/dist/manager/_manager-chunks/globals-runtime-nQMRiA0J.js +19 -0
  321. package/dist/manager/_manager-chunks/globals-runtime-oRjPg2jY.js +8935 -0
  322. package/dist/manager/_manager-chunks/{globals-runtime-sGpNlIJ1.js → globals-runtime-wV08sCKl.js} +715 -620
  323. package/dist/manager/_manager-chunks/{runtime-cp5pazY2.js → runtime-4OQZWibO.js} +1717 -1536
  324. package/dist/manager/_manager-chunks/runtime-BYxbyNm0.js +201 -0
  325. package/dist/manager/_manager-chunks/{runtime-EITvVbkG.js → runtime-BdGkqNEt.js} +1 -2
  326. package/dist/manager/_manager-chunks/runtime-CM4Z8aKR.js +735 -0
  327. package/dist/manager/_manager-chunks/{runtime-eDVAYF7N.js → runtime-Cjo1UL1u.js} +57 -76
  328. package/dist/manager/_manager-chunks/runtime-Cx1-wr6J.js +294 -0
  329. package/dist/manager/_manager-chunks/{runtime-BhkT2CXl.js → runtime-Cxe_uJRb.js} +220 -406
  330. package/dist/manager/_manager-chunks/runtime-D702FFTO.js +551 -0
  331. package/dist/manager/_manager-chunks/{runtime-D94Vq3oR.js → runtime-DnWFp6Zw.js} +8 -534
  332. package/dist/manager/_manager-chunks/{runtime-D0UOWx0U.js → runtime-DoYPE6g6.js} +232 -158
  333. package/dist/manager/_manager-chunks/runtime-P663lpsR.js +528 -0
  334. package/dist/manager/_manager-chunks/{runtime-i-PDAHLR.js → runtime-sppa-0ll.js} +741 -698
  335. package/dist/manager/globals-runtime.js +1 -1
  336. package/dist/manager/globals.d.ts +12 -12
  337. package/dist/manager/globals.js +12 -12
  338. package/dist/manager/runtime.js +1 -1
  339. package/dist/manager-api/index.d.ts +1 -1
  340. package/dist/manager-api/index.js +538 -528
  341. package/dist/manager-errors.d.ts +1 -1
  342. package/dist/manager-errors.js +2 -2
  343. package/dist/mcp/index.d.ts +10 -10
  344. package/dist/mcp/index.js +11 -11
  345. package/dist/mocking-utils/index.d.ts +7 -5
  346. package/dist/mocking-utils/index.js +34 -34
  347. package/dist/mocking-utils/mocker-runtime.js +2 -2
  348. package/dist/next/index.d.ts +231 -0
  349. package/dist/next/index.js +398 -0
  350. package/dist/nextjs-vite/export-mocks/headers/index.js +3 -1
  351. package/dist/nextjs-vite/export-mocks/link/index.d.ts +4 -1
  352. package/dist/nextjs-vite/export-mocks/navigation/index.d.ts +9 -1
  353. package/dist/nextjs-vite/export-mocks/router/index.js +13 -7
  354. package/dist/nextjs-vite/index.d.ts +4 -4
  355. package/dist/nextjs-vite/index.js +10 -5
  356. package/dist/nextjs-vite/node/index.d.ts +2 -2
  357. package/dist/nextjs-vite/node/index.js +7 -7
  358. package/dist/nextjs-vite/node-stand-ins/index.d.ts +68 -0
  359. package/dist/nextjs-vite/node-stand-ins/index.js +145 -0
  360. package/dist/nextjs-vite/preset.js +117 -15
  361. package/dist/nextjs-vite/preview.d.ts +2 -1
  362. package/dist/nextjs-vite/preview.js +1 -1
  363. package/dist/nextjs-vite/vite-plugin/index.d.ts +2 -2
  364. package/dist/nextjs-vite/vite-plugin/index.js +9 -9
  365. package/dist/nextjs-vite-plugin/index.d.ts +2 -3
  366. package/dist/nextjs-vite-plugin/index.js +24 -49
  367. package/dist/nextjs-vite-plugin/mocks/storybook.global.js +8 -8
  368. package/dist/nextjs-vite-plugin/plugins/next-image/alias/next-image.js +2 -2
  369. package/dist/nextjs-vite-plugin/plugins/next-image/alias/next-legacy-image.js +2 -2
  370. package/dist/nextjs-vite-plugin/plugins/next-mocks/alias/router/index.js +10 -6
  371. package/dist/node-logger/index.d.ts +89 -90
  372. package/dist/node-logger/index.js +11 -12
  373. package/dist/oxc-parser/index.js +15 -14
  374. package/dist/oxc-parser/worker.js +10 -10
  375. package/dist/{manager/_manager-chunks/globals-runtime-8HkdnU2F.js → preview/_chunks/runtime-BYRCSYBN.js} +4440 -179
  376. package/dist/preview/_chunks/{runtime-BZSnICCg.js → runtime-Bvh_rfnQ.js} +29 -64
  377. package/dist/preview/_chunks/{runtime-iXdo8CR8.js → runtime-Cbq5WjbL.js} +772 -418
  378. package/dist/preview/_chunks/{runtime-q3wt0e_N.js → runtime-D2MPrqbU.js} +2 -2
  379. package/dist/preview/_chunks/{runtime-DrTjJkPY.js → runtime-DDEUZops.js} +453 -161
  380. package/dist/preview/_chunks/{runtime-BIzIdDbb.js → runtime-DS0s7U3c.js} +482 -334
  381. package/dist/preview/_chunks/{runtime-CsV4HZPV.js → runtime-DsjyhLpG.js} +397 -176
  382. package/dist/preview/_chunks/{runtime-CxZK_Ln3.js → runtime-Dwi6NFcX.js} +3 -3
  383. package/dist/preview/globals.d.ts +10 -10
  384. package/dist/preview/globals.js +10 -10
  385. package/dist/preview/runtime.js +1 -1
  386. package/dist/preview-api/index.d.ts +3 -3
  387. package/dist/preview-api/index.js +12 -10
  388. package/dist/preview-errors.d.ts +1 -1
  389. package/dist/preview-errors.js +2 -2
  390. package/dist/react/docgen/docgen-worker.js +11 -12
  391. package/dist/react/entry-preview-argtypes.js +1 -1
  392. package/dist/react/entry-preview-docs.js +1 -1
  393. package/dist/react/entry-preview.js +2 -1
  394. package/dist/react/index.d.ts +9 -11
  395. package/dist/react/index.js +8 -6
  396. package/dist/react/preset.js +13 -14
  397. package/dist/react/preview.d.ts +1 -1
  398. package/dist/react/preview.js +5 -4
  399. package/dist/react-native/bin/get-stories.js +12 -12
  400. package/dist/react-native/index.d.ts +48 -47
  401. package/dist/react-native/index.js +64 -249
  402. package/dist/react-native/metro/node.d.ts +3 -3
  403. package/dist/react-native/metro/node.js +10 -9
  404. package/dist/react-native/metro/{withStorybook.d.ts → withForkbook.d.ts} +18 -18
  405. package/dist/react-native/metro/{withStorybook.js → withForkbook.js} +27 -26
  406. package/dist/react-native/preview.js +4 -1
  407. package/dist/react-native/scripts/generate.d.ts +1 -1
  408. package/dist/react-native/scripts/generate.js +8 -8
  409. package/dist/react-native/stub.js +1 -1
  410. package/dist/react-native-theming/index.d.ts +2 -58
  411. package/dist/react-native-theming/index.js +63 -2338
  412. package/dist/react-native-ui/index.d.ts +14 -14
  413. package/dist/react-native-ui/index.js +8 -15
  414. package/dist/react-native-ui-common/index.d.ts +32 -12
  415. package/dist/react-native-ui-common/index.js +26 -31
  416. package/dist/react-vite/index.d.ts +2 -2
  417. package/dist/react-vite/node/index.d.ts +3 -3
  418. package/dist/react-vite/node/index.js +7 -7
  419. package/dist/react-vite/preset.d.ts +3 -1
  420. package/dist/react-vite/preset.js +16 -9
  421. package/dist/router/index.d.ts +80 -3
  422. package/dist/router/index.js +66 -12
  423. package/dist/server-errors.d.ts +1 -1
  424. package/dist/server-errors.js +9 -9
  425. package/dist/shared/open-service/index.d.ts +3 -3
  426. package/dist/shared/open-service/index.js +2 -2
  427. package/dist/shared/open-service/services/docgen/worker/docgen-worker.js +9 -9
  428. package/dist/shared/open-service/toolsets/docs/public.d.ts +28 -28
  429. package/dist/telemetry/index.d.ts +38 -274
  430. package/dist/telemetry/index.js +11 -68
  431. package/dist/test/index.d.ts +2 -2
  432. package/dist/test/index.js +765 -511
  433. package/dist/theming/create.d.ts +1 -1
  434. package/dist/theming/create.js +2 -1
  435. package/dist/theming/index.d.ts +6 -6
  436. package/dist/theming/index.js +41 -16
  437. package/dist/types/index.d.ts +2 -2
  438. package/dist/types/index.js +5 -5
  439. package/dist/viewport/index.d.ts +1 -1
  440. package/package.json +69 -69
  441. package/skills/setup/SKILL.md +14 -0
  442. package/skills/stories/SKILL.md +21 -0
  443. package/skills/write-story/SKILL.md +14 -0
  444. package/template/nextjs-vite/cli/js/Button.jsx +2 -2
  445. package/template/nextjs-vite/cli/js/Button.stories.js +6 -6
  446. package/template/nextjs-vite/cli/js/Configure.mdx +100 -100
  447. package/template/nextjs-vite/cli/js/Header.jsx +1 -1
  448. package/template/nextjs-vite/cli/js/Header.stories.js +2 -2
  449. package/template/nextjs-vite/cli/js/Page.jsx +3 -3
  450. package/template/nextjs-vite/cli/js/Page.stories.js +2 -2
  451. package/template/nextjs-vite/cli/ts/Button.stories.ts +6 -6
  452. package/template/nextjs-vite/cli/ts/Button.tsx +2 -2
  453. package/template/nextjs-vite/cli/ts/Configure.mdx +84 -84
  454. package/template/nextjs-vite/cli/ts/Header.stories.ts +2 -2
  455. package/template/nextjs-vite/cli/ts/Header.tsx +1 -1
  456. package/template/nextjs-vite/cli/ts/Page.stories.ts +2 -2
  457. package/template/nextjs-vite/cli/ts/Page.tsx +3 -3
  458. package/template/react/cli/js/Button.jsx +2 -2
  459. package/template/react/cli/js/Button.stories.js +6 -6
  460. package/template/react/cli/js/Header.jsx +1 -1
  461. package/template/react/cli/js/Header.stories.js +2 -2
  462. package/template/react/cli/js/Page.jsx +3 -3
  463. package/template/react/cli/js/Page.stories.js +2 -2
  464. package/template/react/cli/ts/Button.stories.ts +6 -6
  465. package/template/react/cli/ts/Button.tsx +2 -2
  466. package/template/react/cli/ts/Header.stories.ts +2 -2
  467. package/template/react/cli/ts/Header.tsx +1 -1
  468. package/template/react/cli/ts/Page.stories.ts +2 -2
  469. package/template/react/cli/ts/Page.tsx +3 -3
  470. package/template/react-vite/cli/js/Button.jsx +2 -2
  471. package/template/react-vite/cli/js/Button.stories.js +6 -6
  472. package/template/react-vite/cli/js/Header.jsx +1 -1
  473. package/template/react-vite/cli/js/Header.stories.js +2 -2
  474. package/template/react-vite/cli/js/Page.jsx +3 -3
  475. package/template/react-vite/cli/js/Page.stories.js +2 -2
  476. package/template/react-vite/cli/ts/Button.stories.ts +6 -6
  477. package/template/react-vite/cli/ts/Button.tsx +2 -2
  478. package/template/react-vite/cli/ts/Header.stories.ts +2 -2
  479. package/template/react-vite/cli/ts/Header.tsx +1 -1
  480. package/template/react-vite/cli/ts/Page.stories.ts +2 -2
  481. package/template/react-vite/cli/ts/Page.tsx +3 -3
  482. package/assets/browser/nunito-sans-bold-italic.woff2 +0 -0
  483. package/assets/browser/nunito-sans-bold.woff2 +0 -0
  484. package/assets/browser/nunito-sans-italic.woff2 +0 -0
  485. package/assets/browser/nunito-sans-regular.woff2 +0 -0
  486. package/dist/_browser-chunks/WithTooltip-XSQFTBMB.js +0 -1619
  487. package/dist/_browser-chunks/chunk-5P4QA6MY.js +0 -20
  488. package/dist/_browser-chunks/chunk-JMC7AIKT.js +0 -108
  489. package/dist/_node-chunks/builder-manager-VVHYQXCH.js +0 -1661
  490. package/dist/_node-chunks/chunk-2RU7BKEW.js +0 -23
  491. package/dist/_node-chunks/chunk-3BKIBF5S.js +0 -3008
  492. package/dist/_node-chunks/chunk-3T4ZSNPH.js +0 -662
  493. package/dist/_node-chunks/chunk-5DQFEZEA.js +0 -40
  494. package/dist/_node-chunks/chunk-6LMWA44H.js +0 -3837
  495. package/dist/_node-chunks/chunk-BXVYT7SB.js +0 -36
  496. package/dist/_node-chunks/chunk-CQKMLL5J.js +0 -33
  497. package/dist/_node-chunks/chunk-EHUNOMDD.js +0 -52345
  498. package/dist/_node-chunks/chunk-FY6UXW6G.js +0 -11
  499. package/dist/_node-chunks/chunk-GRBLDJCR.js +0 -989
  500. package/dist/_node-chunks/chunk-IDEL2J23.js +0 -23
  501. package/dist/_node-chunks/chunk-JPAZLYJ3.js +0 -29
  502. package/dist/_node-chunks/chunk-MK2KYAI6.js +0 -5414
  503. package/dist/_node-chunks/chunk-NPO45IMH.js +0 -33
  504. package/dist/_node-chunks/chunk-QEQLR22M.js +0 -1877
  505. package/dist/_node-chunks/chunk-RZMQ7S3L.js +0 -92
  506. package/dist/_node-chunks/chunk-SIEXZVCR.js +0 -51
  507. package/dist/_node-chunks/chunk-TEQGGSP7.js +0 -33
  508. package/dist/_node-chunks/chunk-TFCEV2XX.js +0 -155
  509. package/dist/_node-chunks/chunk-UBOGWBEA.js +0 -148
  510. package/dist/_node-chunks/chunk-W4OMYLSP.js +0 -1297
  511. package/dist/_node-chunks/chunk-WAXVSN3O.js +0 -18
  512. package/dist/_node-chunks/chunk-ZMAMXQKP.js +0 -4731
  513. package/dist/_node-chunks/dist-VTSTZKUB.js +0 -16
  514. package/dist/_node-chunks/globby-OEMHPBFY.js +0 -2884
  515. package/dist/_node-chunks/jiti-NFX6UU74.js +0 -3848
  516. package/dist/_node-chunks/lib-MDVARD7W.js +0 -366
  517. package/dist/_node-chunks/optimized-tests-HDOLR3EY.js +0 -22
  518. package/dist/_node-chunks/postinstallAddon-GYGMWDL6.js +0 -20
  519. package/dist/_node-chunks/session-id-KIIVOQLR.js +0 -23
  520. package/dist/chunk-BTVrWliM.d.ts +0 -115
  521. package/dist/chunk-BfBzpgct.d.ts +0 -916
  522. package/dist/chunk-BxWufQms.d.ts +0 -142
  523. package/dist/chunk-DaVb55-_.d.ts +0 -124
  524. package/dist/core-server/presets/common-manager.css +0 -170
  525. package/dist/manager/_manager-chunks/globals-runtime-BIKBO23x.js +0 -3389
  526. package/dist/manager/_manager-chunks/globals-runtime-DkAPXCvc.js +0 -9766
  527. package/dist/manager/_manager-chunks/globals-runtime-DtcOnYHR.js +0 -5357
  528. package/dist/manager/_manager-chunks/globals-runtime-ZHrQFa3-.js +0 -10463
  529. package/dist/manager/_manager-chunks/runtime-B1L9TH89.js +0 -452
  530. package/dist/manager/_manager-chunks/runtime-BK0zF7FN.js +0 -22
  531. package/dist/manager/_manager-chunks/runtime-Bly6WJLN.js +0 -998
  532. package/dist/manager/_manager-chunks/runtime-DMig8mT7.js +0 -77
  533. package/dist/preview/_chunks/runtime-BTPtVY1p.js +0 -1102
  534. package/dist/preview/_chunks/runtime-BwSxqk3t.js +0 -63
  535. package/dist/preview/_chunks/runtime-DZToXfvO.js +0 -9767
  536. package/dist/preview/_chunks/runtime-DuHdxMFA.js +0 -387
@@ -1,10 +1,10 @@
1
- import CJS_COMPAT_NODE_URL_ro17f80mg6k from 'node:url';
2
- import CJS_COMPAT_NODE_PATH_ro17f80mg6k from 'node:path';
3
- import CJS_COMPAT_NODE_MODULE_ro17f80mg6k from "node:module";
1
+ import CJS_COMPAT_NODE_URL_wrk1cj8d1xj from 'node:url';
2
+ import CJS_COMPAT_NODE_PATH_wrk1cj8d1xj from 'node:path';
3
+ import CJS_COMPAT_NODE_MODULE_wrk1cj8d1xj from "node:module";
4
4
 
5
- var __filename = CJS_COMPAT_NODE_URL_ro17f80mg6k.fileURLToPath(import.meta.url);
6
- var __dirname = CJS_COMPAT_NODE_PATH_ro17f80mg6k.dirname(__filename);
7
- var require = CJS_COMPAT_NODE_MODULE_ro17f80mg6k.createRequire(import.meta.url);
5
+ var __filename = CJS_COMPAT_NODE_URL_wrk1cj8d1xj.fileURLToPath(import.meta.url);
6
+ var __dirname = CJS_COMPAT_NODE_PATH_wrk1cj8d1xj.dirname(__filename);
7
+ var require = CJS_COMPAT_NODE_MODULE_wrk1cj8d1xj.createRequire(import.meta.url);
8
8
 
9
9
  // ------------------------------------------------------------
10
10
  // end of CJS compatibility banner, injected by Forkbook's esbuild configuration
@@ -13,81 +13,81 @@ import {
13
13
  fromMarkdown,
14
14
  mdxFromMarkdown,
15
15
  mdxjs
16
- } from "../_node-chunks/chunk-MA24JW6C.js";
16
+ } from "../_node-chunks/chunk-ZHUBTBP2.js";
17
17
  import {
18
18
  require_dist
19
- } from "../_node-chunks/chunk-42UWAGPW.js";
19
+ } from "../_node-chunks/chunk-MWUGCUB5.js";
20
20
  import {
21
21
  BananaSlug
22
- } from "../_node-chunks/chunk-XI6B6P47.js";
22
+ } from "../_node-chunks/chunk-FB5YJWOH.js";
23
+ import {
24
+ withRouteDepth
25
+ } from "../_node-chunks/chunk-VQHM66NL.js";
26
+ import {
27
+ createBasePathMount,
28
+ isForwardedForOrigin,
29
+ resolveBasePath
30
+ } from "../_node-chunks/chunk-OMNGOPNG.js";
23
31
  import {
24
32
  debounce
25
- } from "../_node-chunks/chunk-YCMRA6RX.js";
33
+ } from "../_node-chunks/chunk-CXGOQNGI.js";
26
34
  import {
27
35
  require_lib
28
- } from "../_node-chunks/chunk-3T4ZSNPH.js";
36
+ } from "../_node-chunks/chunk-XDBSAFUB.js";
29
37
  import {
30
38
  Parser,
31
39
  init_acorn,
32
40
  require_acorn_jsx
33
- } from "../_node-chunks/chunk-WCULS5TP.js";
41
+ } from "../_node-chunks/chunk-DP6WFY3D.js";
34
42
  import {
35
43
  isTelemetryModuleEnabled,
36
44
  telemetry,
37
45
  withSpan
38
- } from "../_node-chunks/chunk-W4OMYLSP.js";
39
- import "../_node-chunks/chunk-CQKMLL5J.js";
46
+ } from "../_node-chunks/chunk-KRIOC4WF.js";
40
47
  import {
41
- getEffectiveToolAvailability,
42
- getManifestStatus,
43
- getToolAvailability,
44
- isAddonA11yEnabled,
45
- isAddonVitestEnabled,
46
- isClaudePreviewLaunch,
47
- isModuleGraphSupported,
48
- resolveSkillInputs
49
- } from "../_node-chunks/chunk-UBOGWBEA.js";
48
+ isCsfFactoryPreview,
49
+ readConfig
50
+ } from "../_node-chunks/chunk-3D6N6P2R.js";
51
+ import {
52
+ require_src
53
+ } from "../_node-chunks/chunk-E3ZFMURC.js";
54
+ import "../_node-chunks/chunk-D5V6CZ6U.js";
55
+ import {
56
+ isClaudePreviewLaunch
57
+ } from "../_node-chunks/chunk-CJHRH777.js";
50
58
  import {
51
59
  CLAUDE_PREVIEW_AGENT_NAME
52
- } from "../_node-chunks/chunk-TWI4GVH7.js";
53
- import "../_node-chunks/chunk-B5J7Q7J4.js";
54
- import "../_node-chunks/chunk-5DQFEZEA.js";
55
- import "../_node-chunks/chunk-WAXVSN3O.js";
60
+ } from "../_node-chunks/chunk-S6VCOSQS.js";
56
61
  import {
57
- detectAgent
58
- } from "../_node-chunks/chunk-DHJFTB4K.js";
59
- import "../_node-chunks/chunk-JZOO7GGC.js";
60
- import "../_node-chunks/chunk-V2DY426G.js";
62
+ frameworkToRendererMap
63
+ } from "../_node-chunks/chunk-PLIQQETC.js";
64
+ import "../_node-chunks/chunk-HSX6BDBA.js";
61
65
  import {
62
- userOrAutoTitleFromSpecifier
63
- } from "../_node-chunks/chunk-UMUBKI6E.js";
64
- import "../_node-chunks/chunk-JGGFYIG5.js";
65
- import "../_node-chunks/chunk-UVINFLGY.js";
66
- import "../_node-chunks/chunk-FPZB5OI7.js";
66
+ detectAgent
67
+ } from "../_node-chunks/chunk-YXEKWVJQ.js";
68
+ import "../_node-chunks/chunk-SFT6ZAVN.js";
67
69
  import {
70
+ defaultConfigDir,
71
+ extractFrameworkPackageName,
72
+ findConfigFile,
68
73
  resolveImport,
69
- supportedExtensions
70
- } from "../_node-chunks/chunk-GRBLDJCR.js";
71
- import "../_node-chunks/chunk-SWO5CDYU.js";
72
- import "../_node-chunks/chunk-YZFWBA5L.js";
73
- import {
74
- require_src
75
- } from "../_node-chunks/chunk-GEFQN7K3.js";
76
- import "../_node-chunks/chunk-BS2WMZMR.js";
77
- import "../_node-chunks/chunk-2DSIDINN.js";
78
- import "../_node-chunks/chunk-3BKIBF5S.js";
79
- import "../_node-chunks/chunk-SIEXZVCR.js";
80
- import "../_node-chunks/chunk-RZMQ7S3L.js";
74
+ supportedExtensions,
75
+ userOrAutoTitleFromSpecifier
76
+ } from "../_node-chunks/chunk-IPFPWMT5.js";
77
+ import "../_node-chunks/chunk-CVHDAEDZ.js";
78
+ import "../_node-chunks/chunk-C6HQ6WLU.js";
79
+ import "../_node-chunks/chunk-ROJ6RSIJ.js";
80
+ import "../_node-chunks/chunk-LYS7TI35.js";
81
+ import "../_node-chunks/chunk-GP6YBA2R.js";
82
+ import "../_node-chunks/chunk-6IPHWCFI.js";
81
83
  import {
82
- logger,
83
- require_pretty_hrtime
84
- } from "../_node-chunks/chunk-6LMWA44H.js";
84
+ logger
85
+ } from "../_node-chunks/chunk-MDTXL6SN.js";
85
86
  import {
86
87
  ChangeDetectionFailureError,
87
88
  ChangeDetectionUnavailableError,
88
89
  GitDiffProvider,
89
90
  MDX_SERVICE_ID,
90
- analyzeTestResults,
91
91
  applyServicesPresetOnce,
92
92
  createDocsToolset,
93
93
  createLocalDocsAccess,
@@ -98,17 +98,15 @@ import {
98
98
  emptyManifests,
99
99
  findStoryIds,
100
100
  fullStatusStore,
101
- fullTestProviderStore,
102
101
  getBuilders,
103
102
  getChangeDetectionReadiness,
104
- getComponentCandidates,
105
103
  getErrorLevel,
106
104
  getManagerBuilder,
105
+ getOrRecreateStore,
107
106
  getPreviewBuilder,
108
107
  getRefsFromConfig,
109
108
  getStatusStoreByTypeId,
110
109
  getStoryIdsByAbsolutePath,
111
- getTestProviderStoreById,
112
110
  getWsToken,
113
111
  loadManifests,
114
112
  mapStaticDir,
@@ -120,91 +118,96 @@ import {
120
118
  resetServicesPresetOnce,
121
119
  resolveChangeDetectionAdapter,
122
120
  reviewToolset,
123
- runStoryTests,
124
121
  sendTelemetryError,
125
122
  setChangeDetectionHost,
126
123
  setChangeDetectionReadiness,
127
124
  storyInputArraySchema,
128
- toStoryTestResult,
129
125
  universalStatusStore,
130
- universalTestProviderStore,
131
126
  useStatics,
132
127
  withTelemetry,
133
128
  writeManifests
134
- } from "../_node-chunks/chunk-E6YESGLX.js";
129
+ } from "../_node-chunks/chunk-S2NB6QEG.js";
135
130
  import {
136
131
  UniversalStore
137
- } from "../_node-chunks/chunk-OISX4AGQ.js";
132
+ } from "../_node-chunks/chunk-NP2JHOFY.js";
133
+ import {
134
+ buildStoryPathMap,
135
+ urlPathDepth
136
+ } from "../_node-chunks/chunk-GEWVOY3F.js";
138
137
  import {
139
138
  init_build,
140
139
  parse
141
- } from "../_node-chunks/chunk-XGIUVY52.js";
142
- import "../_node-chunks/chunk-TFCEV2XX.js";
143
- import "../_node-chunks/chunk-Q7QNUM5H.js";
140
+ } from "../_node-chunks/chunk-4UTCKJEQ.js";
141
+ import {
142
+ joinBasePath,
143
+ normalizeBasePath
144
+ } from "../_node-chunks/chunk-PHWMAF5C.js";
145
+ import "../_node-chunks/chunk-4C3ACAHV.js";
144
146
  import {
145
147
  registerToolset
146
- } from "../_node-chunks/chunk-3Y6AAY5H.js";
147
- import "../_node-chunks/chunk-BSKFCWQD.js";
148
- import "../_node-chunks/chunk-ICPBH3E7.js";
149
- import "../_node-chunks/chunk-EWOX7HPJ.js";
148
+ } from "../_node-chunks/chunk-3ER54PQM.js";
149
+ import "../_node-chunks/chunk-5QG6AXK4.js";
150
+ import "../_node-chunks/chunk-7P67PUU2.js";
151
+ import "../_node-chunks/chunk-6HQJJDLH.js";
150
152
  import {
151
153
  STORY_FILE_TEST_REGEXP,
152
- getStoryImportPathFromEntry,
153
- require_cross_spawn
154
- } from "../_node-chunks/chunk-MK2KYAI6.js";
155
- import "../_node-chunks/chunk-IDEL2J23.js";
156
- import "../_node-chunks/chunk-BXVYT7SB.js";
154
+ getStoryImportPathFromEntry
155
+ } from "../_node-chunks/chunk-53A5CYDK.js";
156
+ import {
157
+ Tag
158
+ } from "../_node-chunks/chunk-UUAEW2AR.js";
157
159
  import {
158
160
  getService,
159
161
  registerService,
160
162
  writeOpenServiceStaticFiles
161
- } from "../_node-chunks/chunk-SLWQNBGO.js";
163
+ } from "../_node-chunks/chunk-E23GDXG6.js";
162
164
  import {
163
165
  Channel,
164
166
  describeService,
165
167
  getRegisteredServices,
166
168
  listServices
167
- } from "../_node-chunks/chunk-4FEANXWU.js";
168
- import "../_node-chunks/chunk-TEQGGSP7.js";
169
- import "../_node-chunks/chunk-OWNFOGTA.js";
170
- import "../_node-chunks/chunk-HMP2G23X.js";
171
- import "../_node-chunks/chunk-3W7F2B7P.js";
172
- import "../_node-chunks/chunk-OUW6R7C3.js";
169
+ } from "../_node-chunks/chunk-53PSBDRK.js";
173
170
  import {
174
- Tag
175
- } from "../_node-chunks/chunk-SVTBJ7Q3.js";
176
- import "../_node-chunks/chunk-WNZ2UMFM.js";
177
- import "../_node-chunks/chunk-RRN2V55B.js";
171
+ isEqual
172
+ } from "../_node-chunks/chunk-XTQQGAUZ.js";
173
+ import "../_node-chunks/chunk-H4CRQDTK.js";
174
+ import "../_node-chunks/chunk-54MO4QLB.js";
175
+ import "../_node-chunks/chunk-3335ZZIO.js";
176
+ import "../_node-chunks/chunk-TGF6Q66I.js";
177
+ import "../_node-chunks/chunk-SXBUK4F6.js";
178
178
  import {
179
179
  up2 as up
180
- } from "../_node-chunks/chunk-JDXXX6LB.js";
180
+ } from "../_node-chunks/chunk-MX5MVLEK.js";
181
181
  import {
182
182
  invariant
183
- } from "../_node-chunks/chunk-34EO2PUT.js";
183
+ } from "../_node-chunks/chunk-GQUFGJ4D.js";
184
184
  import {
185
185
  resolvePackageDir,
186
186
  safeResolveModule
187
- } from "../_node-chunks/chunk-F3ZFKBHY.js";
188
- import "../_node-chunks/chunk-TNJIXE37.js";
187
+ } from "../_node-chunks/chunk-PC57BIYZ.js";
188
+ import "../_node-chunks/chunk-7IAYDGYH.js";
189
189
  import {
190
190
  StorybookError
191
- } from "../_node-chunks/chunk-U5W53R2J.js";
191
+ } from "../_node-chunks/chunk-HGJMP4EI.js";
192
192
  import {
193
193
  require_picocolors
194
- } from "../_node-chunks/chunk-2BUPBPFB.js";
194
+ } from "../_node-chunks/chunk-HCDG54OG.js";
195
195
  import {
196
196
  storyIndexPathToAbsolutePath
197
- } from "../_node-chunks/chunk-XLP2ZKXV.js";
198
- import "../_node-chunks/chunk-FW2HQUBQ.js";
197
+ } from "../_node-chunks/chunk-AAK5BBF2.js";
198
+ import "../_node-chunks/chunk-ZHUBOYOD.js";
199
199
  import {
200
200
  slash
201
- } from "../_node-chunks/chunk-DC7DKR5K.js";
202
- import "../_node-chunks/chunk-ZMAMXQKP.js";
201
+ } from "../_node-chunks/chunk-3H5C52QU.js";
202
+ import {
203
+ glob
204
+ } from "../_node-chunks/chunk-TTLSBLPQ.js";
205
+ import "../_node-chunks/chunk-Z6CUUWJO.js";
203
206
  import {
204
207
  __commonJS,
205
208
  __require,
206
209
  __toESM
207
- } from "../_node-chunks/chunk-CXRU72ET.js";
210
+ } from "../_node-chunks/chunk-YMJVSFJT.js";
208
211
 
209
212
  // ../../node_modules/@discoveryjs/json-ext/package.json
210
213
  var require_package = __commonJS({
@@ -707,7 +710,7 @@ var require_parse_chunked = __commonJS({
707
710
  module.exports = function(chunkEmitter) {
708
711
  let parser = new ChunkParser();
709
712
  if (isObject(chunkEmitter) && isReadableStream(chunkEmitter))
710
- return new Promise((resolve9, reject) => {
713
+ return new Promise((resolve10, reject) => {
711
714
  chunkEmitter.on("data", (chunk) => {
712
715
  try {
713
716
  parser.push(chunk);
@@ -718,7 +721,7 @@ var require_parse_chunked = __commonJS({
718
721
  parser = null, reject(e);
719
722
  }).on("end", () => {
720
723
  try {
721
- resolve9(parser.finish());
724
+ resolve10(parser.finish());
722
725
  } catch (e) {
723
726
  reject(adjustPosition(e, parser));
724
727
  } finally {
@@ -729,11 +732,11 @@ var require_parse_chunked = __commonJS({
729
732
  if (typeof chunkEmitter == "function") {
730
733
  let iterator = chunkEmitter();
731
734
  if (isObject(iterator) && (Symbol.iterator in iterator || Symbol.asyncIterator in iterator))
732
- return new Promise(async (resolve9, reject) => {
735
+ return new Promise(async (resolve10, reject) => {
733
736
  try {
734
737
  for await (let chunk of iterator)
735
738
  parser.push(chunk);
736
- resolve9(parser.finish());
739
+ resolve10(parser.finish());
737
740
  } catch (e) {
738
741
  reject(adjustPosition(e, parser));
739
742
  } finally {
@@ -881,6 +884,361 @@ var require_src2 = __commonJS({
881
884
  }
882
885
  });
883
886
 
887
+ // ../../node_modules/isexe/windows.js
888
+ var require_windows = __commonJS({
889
+ "../../node_modules/isexe/windows.js"(exports, module) {
890
+ module.exports = isexe;
891
+ isexe.sync = sync;
892
+ var fs = __require("fs");
893
+ function checkPathExt(path, options) {
894
+ var pathext = options.pathExt !== void 0 ? options.pathExt : process.env.PATHEXT;
895
+ if (!pathext || (pathext = pathext.split(";"), pathext.indexOf("") !== -1))
896
+ return !0;
897
+ for (var i = 0; i < pathext.length; i++) {
898
+ var p = pathext[i].toLowerCase();
899
+ if (p && path.substr(-p.length).toLowerCase() === p)
900
+ return !0;
901
+ }
902
+ return !1;
903
+ }
904
+ function checkStat(stat2, path, options) {
905
+ return !stat2.isSymbolicLink() && !stat2.isFile() ? !1 : checkPathExt(path, options);
906
+ }
907
+ function isexe(path, options, cb) {
908
+ fs.stat(path, function(er, stat2) {
909
+ cb(er, er ? !1 : checkStat(stat2, path, options));
910
+ });
911
+ }
912
+ function sync(path, options) {
913
+ return checkStat(fs.statSync(path), path, options);
914
+ }
915
+ }
916
+ });
917
+
918
+ // ../../node_modules/isexe/mode.js
919
+ var require_mode = __commonJS({
920
+ "../../node_modules/isexe/mode.js"(exports, module) {
921
+ module.exports = isexe;
922
+ isexe.sync = sync;
923
+ var fs = __require("fs");
924
+ function isexe(path, options, cb) {
925
+ fs.stat(path, function(er, stat2) {
926
+ cb(er, er ? !1 : checkStat(stat2, options));
927
+ });
928
+ }
929
+ function sync(path, options) {
930
+ return checkStat(fs.statSync(path), options);
931
+ }
932
+ function checkStat(stat2, options) {
933
+ return stat2.isFile() && checkMode(stat2, options);
934
+ }
935
+ function checkMode(stat2, options) {
936
+ var mod = stat2.mode, uid = stat2.uid, gid = stat2.gid, myUid = options.uid !== void 0 ? options.uid : process.getuid && process.getuid(), myGid = options.gid !== void 0 ? options.gid : process.getgid && process.getgid(), u = parseInt("100", 8), g = parseInt("010", 8), o = parseInt("001", 8), ug = u | g, ret = mod & o || mod & g && gid === myGid || mod & u && uid === myUid || mod & ug && myUid === 0;
937
+ return ret;
938
+ }
939
+ }
940
+ });
941
+
942
+ // ../../node_modules/isexe/index.js
943
+ var require_isexe = __commonJS({
944
+ "../../node_modules/isexe/index.js"(exports, module) {
945
+ var fs = __require("fs"), core;
946
+ process.platform === "win32" || global.TESTING_WINDOWS ? core = require_windows() : core = require_mode();
947
+ module.exports = isexe;
948
+ isexe.sync = sync;
949
+ function isexe(path, options, cb) {
950
+ if (typeof options == "function" && (cb = options, options = {}), !cb) {
951
+ if (typeof Promise != "function")
952
+ throw new TypeError("callback not provided");
953
+ return new Promise(function(resolve10, reject) {
954
+ isexe(path, options || {}, function(er, is) {
955
+ er ? reject(er) : resolve10(is);
956
+ });
957
+ });
958
+ }
959
+ core(path, options || {}, function(er, is) {
960
+ er && (er.code === "EACCES" || options && options.ignoreErrors) && (er = null, is = !1), cb(er, is);
961
+ });
962
+ }
963
+ function sync(path, options) {
964
+ try {
965
+ return core.sync(path, options || {});
966
+ } catch (er) {
967
+ if (options && options.ignoreErrors || er.code === "EACCES")
968
+ return !1;
969
+ throw er;
970
+ }
971
+ }
972
+ }
973
+ });
974
+
975
+ // ../../node_modules/which/which.js
976
+ var require_which = __commonJS({
977
+ "../../node_modules/which/which.js"(exports, module) {
978
+ var isWindows = process.platform === "win32" || process.env.OSTYPE === "cygwin" || process.env.OSTYPE === "msys", path = __require("path"), COLON = isWindows ? ";" : ":", isexe = require_isexe(), getNotFoundError = (cmd) => Object.assign(new Error(`not found: ${cmd}`), { code: "ENOENT" }), getPathInfo = (cmd, opt) => {
979
+ let colon = opt.colon || COLON, pathEnv = cmd.match(/\//) || isWindows && cmd.match(/\\/) ? [""] : [
980
+ // windows always checks the cwd first
981
+ ...isWindows ? [process.cwd()] : [],
982
+ ...(opt.path || process.env.PATH || /* istanbul ignore next: very unusual */
983
+ "").split(colon)
984
+ ], pathExtExe = isWindows ? opt.pathExt || process.env.PATHEXT || ".EXE;.CMD;.BAT;.COM" : "", pathExt = isWindows ? pathExtExe.split(colon) : [""];
985
+ return isWindows && cmd.indexOf(".") !== -1 && pathExt[0] !== "" && pathExt.unshift(""), {
986
+ pathEnv,
987
+ pathExt,
988
+ pathExtExe
989
+ };
990
+ }, which = (cmd, opt, cb) => {
991
+ typeof opt == "function" && (cb = opt, opt = {}), opt || (opt = {});
992
+ let { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt), found = [], step = (i) => new Promise((resolve10, reject) => {
993
+ if (i === pathEnv.length)
994
+ return opt.all && found.length ? resolve10(found) : reject(getNotFoundError(cmd));
995
+ let ppRaw = pathEnv[i], pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw, pCmd = path.join(pathPart, cmd), p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd;
996
+ resolve10(subStep(p, i, 0));
997
+ }), subStep = (p, i, ii) => new Promise((resolve10, reject) => {
998
+ if (ii === pathExt.length)
999
+ return resolve10(step(i + 1));
1000
+ let ext = pathExt[ii];
1001
+ isexe(p + ext, { pathExt: pathExtExe }, (er, is) => {
1002
+ if (!er && is)
1003
+ if (opt.all)
1004
+ found.push(p + ext);
1005
+ else
1006
+ return resolve10(p + ext);
1007
+ return resolve10(subStep(p, i, ii + 1));
1008
+ });
1009
+ });
1010
+ return cb ? step(0).then((res) => cb(null, res), cb) : step(0);
1011
+ }, whichSync = (cmd, opt) => {
1012
+ opt = opt || {};
1013
+ let { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt), found = [];
1014
+ for (let i = 0; i < pathEnv.length; i++) {
1015
+ let ppRaw = pathEnv[i], pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw, pCmd = path.join(pathPart, cmd), p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd;
1016
+ for (let j = 0; j < pathExt.length; j++) {
1017
+ let cur = p + pathExt[j];
1018
+ try {
1019
+ if (isexe.sync(cur, { pathExt: pathExtExe }))
1020
+ if (opt.all)
1021
+ found.push(cur);
1022
+ else
1023
+ return cur;
1024
+ } catch {
1025
+ }
1026
+ }
1027
+ }
1028
+ if (opt.all && found.length)
1029
+ return found;
1030
+ if (opt.nothrow)
1031
+ return null;
1032
+ throw getNotFoundError(cmd);
1033
+ };
1034
+ module.exports = which;
1035
+ which.sync = whichSync;
1036
+ }
1037
+ });
1038
+
1039
+ // ../../node_modules/path-key/index.js
1040
+ var require_path_key = __commonJS({
1041
+ "../../node_modules/path-key/index.js"(exports, module) {
1042
+ "use strict";
1043
+ var pathKey = (options = {}) => {
1044
+ let environment = options.env || process.env;
1045
+ return (options.platform || process.platform) !== "win32" ? "PATH" : Object.keys(environment).reverse().find((key) => key.toUpperCase() === "PATH") || "Path";
1046
+ };
1047
+ module.exports = pathKey;
1048
+ module.exports.default = pathKey;
1049
+ }
1050
+ });
1051
+
1052
+ // ../../node_modules/cross-spawn/lib/util/resolveCommand.js
1053
+ var require_resolveCommand = __commonJS({
1054
+ "../../node_modules/cross-spawn/lib/util/resolveCommand.js"(exports, module) {
1055
+ "use strict";
1056
+ var path = __require("path"), which = require_which(), getPathKey = require_path_key();
1057
+ function resolveCommandAttempt(parsed, withoutPathExt) {
1058
+ let env = parsed.options.env || process.env, cwd = process.cwd(), hasCustomCwd = parsed.options.cwd != null, shouldSwitchCwd = hasCustomCwd && process.chdir !== void 0 && !process.chdir.disabled;
1059
+ if (shouldSwitchCwd)
1060
+ try {
1061
+ process.chdir(parsed.options.cwd);
1062
+ } catch {
1063
+ }
1064
+ let resolved;
1065
+ try {
1066
+ resolved = which.sync(parsed.command, {
1067
+ path: env[getPathKey({ env })],
1068
+ pathExt: withoutPathExt ? path.delimiter : void 0
1069
+ });
1070
+ } catch {
1071
+ } finally {
1072
+ shouldSwitchCwd && process.chdir(cwd);
1073
+ }
1074
+ return resolved && (resolved = path.resolve(hasCustomCwd ? parsed.options.cwd : "", resolved)), resolved;
1075
+ }
1076
+ function resolveCommand(parsed) {
1077
+ return resolveCommandAttempt(parsed) || resolveCommandAttempt(parsed, !0);
1078
+ }
1079
+ module.exports = resolveCommand;
1080
+ }
1081
+ });
1082
+
1083
+ // ../../node_modules/cross-spawn/lib/util/escape.js
1084
+ var require_escape = __commonJS({
1085
+ "../../node_modules/cross-spawn/lib/util/escape.js"(exports, module) {
1086
+ "use strict";
1087
+ var metaCharsRegExp = /([()\][%!^"`<>&|;, *?])/g;
1088
+ function escapeCommand(arg) {
1089
+ return arg = arg.replace(metaCharsRegExp, "^$1"), arg;
1090
+ }
1091
+ function escapeArgument(arg, doubleEscapeMetaChars) {
1092
+ return arg = `${arg}`, arg = arg.replace(/(?=(\\+?)?)\1"/g, '$1$1\\"'), arg = arg.replace(/(?=(\\+?)?)\1$/, "$1$1"), arg = `"${arg}"`, arg = arg.replace(metaCharsRegExp, "^$1"), doubleEscapeMetaChars && (arg = arg.replace(metaCharsRegExp, "^$1")), arg;
1093
+ }
1094
+ module.exports.command = escapeCommand;
1095
+ module.exports.argument = escapeArgument;
1096
+ }
1097
+ });
1098
+
1099
+ // ../../node_modules/shebang-regex/index.js
1100
+ var require_shebang_regex = __commonJS({
1101
+ "../../node_modules/shebang-regex/index.js"(exports, module) {
1102
+ "use strict";
1103
+ module.exports = /^#!(.*)/;
1104
+ }
1105
+ });
1106
+
1107
+ // ../../node_modules/shebang-command/index.js
1108
+ var require_shebang_command = __commonJS({
1109
+ "../../node_modules/shebang-command/index.js"(exports, module) {
1110
+ "use strict";
1111
+ var shebangRegex = require_shebang_regex();
1112
+ module.exports = (string = "") => {
1113
+ let match = string.match(shebangRegex);
1114
+ if (!match)
1115
+ return null;
1116
+ let [path, argument] = match[0].replace(/#! ?/, "").split(" "), binary = path.split("/").pop();
1117
+ return binary === "env" ? argument : argument ? `${binary} ${argument}` : binary;
1118
+ };
1119
+ }
1120
+ });
1121
+
1122
+ // ../../node_modules/cross-spawn/lib/util/readShebang.js
1123
+ var require_readShebang = __commonJS({
1124
+ "../../node_modules/cross-spawn/lib/util/readShebang.js"(exports, module) {
1125
+ "use strict";
1126
+ var fs = __require("fs"), shebangCommand = require_shebang_command();
1127
+ function readShebang(command) {
1128
+ let buffer = Buffer.alloc(150), fd;
1129
+ try {
1130
+ fd = fs.openSync(command, "r"), fs.readSync(fd, buffer, 0, 150, 0), fs.closeSync(fd);
1131
+ } catch {
1132
+ }
1133
+ return shebangCommand(buffer.toString());
1134
+ }
1135
+ module.exports = readShebang;
1136
+ }
1137
+ });
1138
+
1139
+ // ../../node_modules/cross-spawn/lib/parse.js
1140
+ var require_parse = __commonJS({
1141
+ "../../node_modules/cross-spawn/lib/parse.js"(exports, module) {
1142
+ "use strict";
1143
+ var path = __require("path"), resolveCommand = require_resolveCommand(), escape = require_escape(), readShebang = require_readShebang(), isWin = process.platform === "win32", isExecutableRegExp = /\.(?:com|exe)$/i, isCmdShimRegExp = /node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;
1144
+ function detectShebang(parsed) {
1145
+ parsed.file = resolveCommand(parsed);
1146
+ let shebang = parsed.file && readShebang(parsed.file);
1147
+ return shebang ? (parsed.args.unshift(parsed.file), parsed.command = shebang, resolveCommand(parsed)) : parsed.file;
1148
+ }
1149
+ function parseNonShell(parsed) {
1150
+ if (!isWin)
1151
+ return parsed;
1152
+ let commandFile = detectShebang(parsed), needsShell = !isExecutableRegExp.test(commandFile);
1153
+ if (parsed.options.forceShell || needsShell) {
1154
+ let needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile);
1155
+ parsed.command = path.normalize(parsed.command), parsed.command = escape.command(parsed.command), parsed.args = parsed.args.map((arg) => escape.argument(arg, needsDoubleEscapeMetaChars));
1156
+ let shellCommand = [parsed.command].concat(parsed.args).join(" ");
1157
+ parsed.args = ["/d", "/s", "/c", `"${shellCommand}"`], parsed.command = process.env.comspec || "cmd.exe", parsed.options.windowsVerbatimArguments = !0;
1158
+ }
1159
+ return parsed;
1160
+ }
1161
+ function parse5(command, args, options) {
1162
+ args && !Array.isArray(args) && (options = args, args = null), args = args ? args.slice(0) : [], options = Object.assign({}, options);
1163
+ let parsed = {
1164
+ command,
1165
+ args,
1166
+ options,
1167
+ file: void 0,
1168
+ original: {
1169
+ command,
1170
+ args
1171
+ }
1172
+ };
1173
+ return options.shell ? parsed : parseNonShell(parsed);
1174
+ }
1175
+ module.exports = parse5;
1176
+ }
1177
+ });
1178
+
1179
+ // ../../node_modules/cross-spawn/lib/enoent.js
1180
+ var require_enoent = __commonJS({
1181
+ "../../node_modules/cross-spawn/lib/enoent.js"(exports, module) {
1182
+ "use strict";
1183
+ var isWin = process.platform === "win32";
1184
+ function notFoundError(original, syscall) {
1185
+ return Object.assign(new Error(`${syscall} ${original.command} ENOENT`), {
1186
+ code: "ENOENT",
1187
+ errno: "ENOENT",
1188
+ syscall: `${syscall} ${original.command}`,
1189
+ path: original.command,
1190
+ spawnargs: original.args
1191
+ });
1192
+ }
1193
+ function hookChildProcess(cp3, parsed) {
1194
+ if (!isWin)
1195
+ return;
1196
+ let originalEmit = cp3.emit;
1197
+ cp3.emit = function(name, arg1) {
1198
+ if (name === "exit") {
1199
+ let err = verifyENOENT(arg1, parsed);
1200
+ if (err)
1201
+ return originalEmit.call(cp3, "error", err);
1202
+ }
1203
+ return originalEmit.apply(cp3, arguments);
1204
+ };
1205
+ }
1206
+ function verifyENOENT(status, parsed) {
1207
+ return isWin && status === 1 && !parsed.file ? notFoundError(parsed.original, "spawn") : null;
1208
+ }
1209
+ function verifyENOENTSync(status, parsed) {
1210
+ return isWin && status === 1 && !parsed.file ? notFoundError(parsed.original, "spawnSync") : null;
1211
+ }
1212
+ module.exports = {
1213
+ hookChildProcess,
1214
+ verifyENOENT,
1215
+ verifyENOENTSync,
1216
+ notFoundError
1217
+ };
1218
+ }
1219
+ });
1220
+
1221
+ // ../../node_modules/cross-spawn/index.js
1222
+ var require_cross_spawn = __commonJS({
1223
+ "../../node_modules/cross-spawn/index.js"(exports, module) {
1224
+ "use strict";
1225
+ var cp3 = __require("child_process"), parse5 = require_parse(), enoent = require_enoent();
1226
+ function spawn2(command, args, options) {
1227
+ let parsed = parse5(command, args, options), spawned = cp3.spawn(parsed.command, parsed.args, parsed.options);
1228
+ return enoent.hookChildProcess(spawned, parsed), spawned;
1229
+ }
1230
+ function spawnSync(command, args, options) {
1231
+ let parsed = parse5(command, args, options), result = cp3.spawnSync(parsed.command, parsed.args, parsed.options);
1232
+ return result.error = result.error || enoent.verifyENOENTSync(result.status, parsed), result;
1233
+ }
1234
+ module.exports = spawn2;
1235
+ module.exports.spawn = spawn2;
1236
+ module.exports.sync = spawnSync;
1237
+ module.exports._parse = parse5;
1238
+ module.exports._enoent = enoent;
1239
+ }
1240
+ });
1241
+
884
1242
  // ../../node_modules/address/lib/address.js
885
1243
  var require_address = __commonJS({
886
1244
  "../../node_modules/address/lib/address.js"(exports, module) {
@@ -999,9 +1357,9 @@ var require_detect_port = __commonJS({
999
1357
  let hostname = "";
1000
1358
  typeof port == "object" && port ? (hostname = port.hostname, callback = port.callback, port = port.port) : typeof port == "function" && (callback = port, port = null), port = parseInt(port) || 0;
1001
1359
  let maxPort = port + 10;
1002
- return maxPort > 65535 && (maxPort = 65535), debug("detect free port between [%s, %s)", port, maxPort), typeof callback == "function" ? tryListen(port, maxPort, hostname, callback) : new Promise((resolve9) => {
1360
+ return maxPort > 65535 && (maxPort = 65535), debug("detect free port between [%s, %s)", port, maxPort), typeof callback == "function" ? tryListen(port, maxPort, hostname, callback) : new Promise((resolve10) => {
1003
1361
  tryListen(port, maxPort, hostname, (_, realPort) => {
1004
- resolve9(realPort);
1362
+ resolve10(realPort);
1005
1363
  });
1006
1364
  });
1007
1365
  };
@@ -1044,7 +1402,7 @@ var require_detect_port = __commonJS({
1044
1402
  var require_wait_port = __commonJS({
1045
1403
  "../../node_modules/detect-port/lib/wait-port.js"(exports, module) {
1046
1404
  "use strict";
1047
- var debug = require_src()("wait-port"), detect = require_detect_port(), sleep = (ms) => new Promise((resolve9) => setTimeout(resolve9, ms));
1405
+ var debug = require_src()("wait-port"), detect = require_detect_port(), sleep = (ms) => new Promise((resolve10) => setTimeout(resolve10, ms));
1048
1406
  async function waitPort(port, options = {}) {
1049
1407
  let { retryInterval = 1e3, retries = 1 / 0 } = options, count = 1;
1050
1408
  async function loop() {
@@ -1076,8 +1434,7 @@ import {
1076
1434
  } from "@aussieljk/forkbook/internal/common";
1077
1435
 
1078
1436
  // src/core-server/build-static.ts
1079
- var import_picocolors3 = __toESM(require_picocolors(), 1);
1080
- import { cp as cp2, mkdir } from "node:fs/promises";
1437
+ import { cp as cp2, mkdir as mkdir3 } from "node:fs/promises";
1081
1438
  import { rm } from "node:fs/promises";
1082
1439
  import { Channel as Channel2 } from "@aussieljk/forkbook/internal/channels";
1083
1440
  import {
@@ -1087,9 +1444,14 @@ import {
1087
1444
  resolveAddonName
1088
1445
  } from "@aussieljk/forkbook/internal/common";
1089
1446
  import { logger as logger4 } from "@aussieljk/forkbook/internal/node-logger";
1090
- import { getPrecedingUpgrade, telemetry as telemetry2 } from "@aussieljk/forkbook/internal/telemetry";
1091
- import { global as global2 } from "@storybook/global";
1092
- import { join as join4, relative as relative3, resolve as resolve3 } from "pathe";
1447
+ import { telemetry as telemetry2 } from "@aussieljk/forkbook/internal/telemetry";
1448
+
1449
+ // src/shared/global.ts
1450
+ var global2 = globalThis;
1451
+
1452
+ // src/core-server/build-static.ts
1453
+ var import_picocolors3 = __toESM(require_picocolors(), 1);
1454
+ import { join as join6, relative as relative4, resolve as resolve4 } from "pathe";
1093
1455
 
1094
1456
  // src/core-server/utils/build-or-throw.ts
1095
1457
  import { NoMatchingExportError } from "@aussieljk/forkbook/internal/server-errors";
@@ -1100,7 +1462,7 @@ async function buildOrThrow(callback) {
1100
1462
  let builderErrors = err.errors;
1101
1463
  throw builderErrors && builderErrors.find(
1102
1464
  (er) => er.text?.includes("No matching export")
1103
- ) ? new NoMatchingExportError(err) : err;
1465
+ ) ? new NoMatchingExportError({ error: err }) : err;
1104
1466
  }
1105
1467
  }
1106
1468
 
@@ -1112,9 +1474,7 @@ import { logger as logger2 } from "@aussieljk/forkbook/internal/node-logger";
1112
1474
  async function copyAllStaticFilesRelativeToMain(staticDirs, outputDir, configDir) {
1113
1475
  return staticDirs?.reduce(async (acc, dir) => {
1114
1476
  await acc;
1115
- let { staticPath: from, targetEndpoint: to } = mapStaticDir(dir, configDir), targetPath = join(outputDir, to), skipPaths = ["index.html", "iframe.html", "index.json", "project.json"].map(
1116
- (f) => resolve(outputDir, f)
1117
- );
1477
+ let { staticPath: from, targetEndpoint: to } = mapStaticDir(dir, configDir), targetPath = join(outputDir, to), skipPaths = ["index.html", "iframe.html", "index.json"].map((f) => resolve(outputDir, f));
1118
1478
  from.includes("node_modules") || logger2.info(
1119
1479
  `Copying static files: ${import_picocolors.default.cyan(print(from))} at ${import_picocolors.default.cyan(print(targetPath))}`
1120
1480
  ), await cp(from, targetPath, {
@@ -1184,8 +1544,11 @@ function watchStorySpecifiers(specifiers, options, onInvalidate) {
1184
1544
  // files can be e.g. '**/foo/*/*.js' so we just want the last bit,
1185
1545
  // because the directory could already be within the files part (e.g. './x/foo/bar')
1186
1546
  basename(specifier.files)
1187
- ), { globby } = await import("../_node-chunks/globby-OEMHPBFY.js");
1188
- (await globby(slash(dirGlob), commonGlobOptions(dirGlob))).forEach((filePath) => {
1547
+ ), { glob: glob2 } = await import("../_node-chunks/dist-XPLJ5T4W.js");
1548
+ (await glob2(slash(dirGlob), {
1549
+ ...commonGlobOptions(dirGlob),
1550
+ expandDirectories: !1
1551
+ })).forEach((filePath) => {
1189
1552
  let fileImportPath = toImportPath(filePath);
1190
1553
  specifier.importPathMatcher.exec(fileImportPath) && onInvalidate(fileImportPath, removed);
1191
1554
  });
@@ -1237,7 +1600,7 @@ function registerIndexJsonRoute({
1237
1600
  basename2(filePath).startsWith("preview") && ((await storyIndexGeneratorPromise).invalidateAll(), maybeInvalidate());
1238
1601
  }), app.use("/index.json", async (_req, res) => {
1239
1602
  try {
1240
- let index = await (await storyIndexGeneratorPromise).getIndex();
1603
+ let index = await (await storyIndexGeneratorPromise).getIndexWithFileErrors();
1241
1604
  res.setHeader("Content-Type", "application/json"), res.setHeader("Access-Control-Allow-Origin", "*"), res.setHeader(
1242
1605
  "Access-Control-Allow-Headers",
1243
1606
  "Origin, X-Requested-With, Content-Type, Accept"
@@ -1248,24 +1611,102 @@ function registerIndexJsonRoute({
1248
1611
  });
1249
1612
  }
1250
1613
 
1251
- // src/core-server/utils/metadata.ts
1252
- import { writeFile as writeFile2 } from "node:fs/promises";
1253
- import { getStorybookMetadata } from "@aussieljk/forkbook/internal/telemetry";
1254
- async function extractStorybookMetadata(outputFile, configDir) {
1255
- let storybookMetadata = await getStorybookMetadata(configDir);
1256
- await writeFile2(outputFile, JSON.stringify(storybookMetadata));
1257
- }
1258
- function useStorybookMetadata(app, configDir) {
1259
- app.use("/project.json", async (req, res) => {
1260
- let storybookMetadata = await getStorybookMetadata(configDir);
1261
- res.setHeader("Content-Type", "application/json"), res.write(JSON.stringify(storybookMetadata)), res.end();
1614
+ // src/core-server/utils/thumbnails.ts
1615
+ import { copyFile, mkdir, readFile } from "node:fs/promises";
1616
+ import { dirname as dirname2, join as join3 } from "pathe";
1617
+
1618
+ // src/shared/thumbnails.ts
1619
+ import { dirname, isAbsolute, normalize, relative as relative3, resolve as resolve3 } from "pathe";
1620
+ var THUMBNAIL_ROUTE = "thumbnails", THUMBNAIL_TYPES = {
1621
+ avif: "image/avif",
1622
+ gif: "image/gif",
1623
+ jpeg: "image/jpeg",
1624
+ jpg: "image/jpeg",
1625
+ png: "image/png",
1626
+ svg: "image/svg+xml",
1627
+ webp: "image/webp"
1628
+ }, extension = (path) => path.split(".").pop()?.toLowerCase() ?? "", isThumbnailUrl = (value) => /^([a-z][a-z\d+.-]*:|\/\/|\/)/i.test(value), resolveThumbnail = (value, storyFile, workingDir) => {
1629
+ if (!value)
1630
+ return;
1631
+ if (isThumbnailUrl(value) && !isAbsolute(value))
1632
+ return value;
1633
+ let file = isAbsolute(value) ? value : resolve3(dirname(storyFile), value);
1634
+ if (isAbsolute(value) && !normalize(value).startsWith(normalize(workingDir)))
1635
+ return value;
1636
+ let path = relative3(workingDir, file);
1637
+ if (!(path.startsWith("..") || !THUMBNAIL_TYPES[extension(path)]))
1638
+ return `${THUMBNAIL_ROUTE}/${path}`;
1639
+ }, thumbnailFile = (urlPath, workingDir) => {
1640
+ let path = urlPath.replace(/^\/+/, "");
1641
+ try {
1642
+ path = decodeURIComponent(path);
1643
+ } catch {
1644
+ return;
1645
+ }
1646
+ if (!path.startsWith(`${THUMBNAIL_ROUTE}/`))
1647
+ return;
1648
+ let file = resolve3(workingDir, path.slice(THUMBNAIL_ROUTE.length + 1));
1649
+ if (!(relative3(workingDir, file).startsWith("..") || !THUMBNAIL_TYPES[extension(file)]))
1650
+ return file;
1651
+ }, thumbnailContentType = (file) => THUMBNAIL_TYPES[extension(file)] ?? "application/octet-stream";
1652
+
1653
+ // src/core-server/utils/thumbnails.ts
1654
+ function registerThumbnailRoute(app, workingDir) {
1655
+ app.use(`/${THUMBNAIL_ROUTE}`, async (req, res) => {
1656
+ let url = (req.originalUrl ?? req.url ?? "").split("?")[0], file = thumbnailFile(url, workingDir);
1657
+ try {
1658
+ if (!file)
1659
+ throw new Error("Not a thumbnail");
1660
+ let body = await readFile(file);
1661
+ res.setHeader("Content-Type", thumbnailContentType(file)), res.end(body);
1662
+ } catch {
1663
+ res.statusCode = 404, res.end("Not found");
1664
+ }
1262
1665
  });
1263
1666
  }
1667
+ async function copyThumbnails(outputDir, index, workingDir) {
1668
+ let paths = new Set(
1669
+ Object.values(index.entries).map((entry) => entry.thumbnail).filter((path) => !!path && path.startsWith(`${THUMBNAIL_ROUTE}/`))
1670
+ ), count = 0;
1671
+ return await Promise.all(
1672
+ [...paths].map(async (path) => {
1673
+ let file = thumbnailFile(path, workingDir);
1674
+ if (!file)
1675
+ return;
1676
+ let target = join3(outputDir, path);
1677
+ await mkdir(dirname2(target), { recursive: !0 }), await copyFile(file, target).then(
1678
+ () => count++,
1679
+ () => {
1680
+ }
1681
+ );
1682
+ })
1683
+ ), count;
1684
+ }
1685
+
1686
+ // src/core-server/utils/write-route-pages.ts
1687
+ import { mkdir as mkdir2, readFile as readFile2, writeFile as writeFile2 } from "node:fs/promises";
1688
+ import { join as join4 } from "pathe";
1689
+ var STATIC_APP_ROUTES = [
1690
+ "/all",
1691
+ "/review",
1692
+ "/settings/about",
1693
+ "/settings/shortcuts",
1694
+ "/settings/whats-new"
1695
+ ];
1696
+ async function writeRoutePages(outputDir, index) {
1697
+ let html = await readFile2(join4(outputDir, "index.html"), "utf8"), urlPaths = [...buildStoryPathMap(Object.values(index.entries)).byUrl.keys()], allPaths = [...STATIC_APP_ROUTES, ...urlPaths];
1698
+ return await Promise.all(
1699
+ allPaths.map(async (urlPath) => {
1700
+ let dir = join4(outputDir, urlPath);
1701
+ await mkdir2(dir, { recursive: !0 }), await writeFile2(join4(dir, "index.html"), withRouteDepth(html, urlPathDepth(urlPath)));
1702
+ })
1703
+ ), allPaths.length;
1704
+ }
1264
1705
 
1265
1706
  // src/core-server/utils/output-stats.ts
1266
1707
  var import_json_ext = __toESM(require_src2(), 1), import_picocolors2 = __toESM(require_picocolors(), 1);
1267
1708
  import { createWriteStream } from "node:fs";
1268
- import { join as join3 } from "node:path";
1709
+ import { join as join5 } from "node:path";
1269
1710
  import { logger as logger3 } from "@aussieljk/forkbook/internal/node-logger";
1270
1711
  async function outputStats(directory, previewStats, managerStats) {
1271
1712
  if (previewStats) {
@@ -1278,9 +1719,9 @@ async function outputStats(directory, previewStats, managerStats) {
1278
1719
  }
1279
1720
  }
1280
1721
  var writeStats = async (directory, name, stats) => {
1281
- let filePath = join3(directory, `${name}-stats.json`), { chunks, ...data } = stats.toJson();
1282
- return await new Promise((resolve9, reject) => {
1283
- (0, import_json_ext.stringifyStream)(data, null, 2).on("error", reject).pipe(createWriteStream(filePath)).on("error", reject).on("finish", resolve9);
1722
+ let filePath = join5(directory, `${name}-stats.json`), { chunks, ...data } = stats.toJson();
1723
+ return await new Promise((resolve10, reject) => {
1724
+ (0, import_json_ext.stringifyStream)(data, null, 2).on("error", reject).pipe(createWriteStream(filePath)).on("error", reject).on("finish", resolve10);
1284
1725
  }), filePath;
1285
1726
  };
1286
1727
 
@@ -1332,16 +1773,40 @@ function summarizeIndex(storyIndex) {
1332
1773
  }
1333
1774
 
1334
1775
  // src/core-server/build-static.ts
1776
+ var DEFAULT_STATIC_OUTPUT_DIR = "./forkbook-static";
1777
+ function resolveStaticOutputDir({
1778
+ outputDir,
1779
+ buildToPublic,
1780
+ basePath
1781
+ }) {
1782
+ if (outputDir)
1783
+ return outputDir;
1784
+ if (buildToPublic) {
1785
+ if (!basePath)
1786
+ throw new Error('buildToPublic needs a base path other than "/".');
1787
+ return join6("public", basePath);
1788
+ }
1789
+ return DEFAULT_STATIC_OUTPUT_DIR;
1790
+ }
1335
1791
  async function buildStaticStandalone(options) {
1336
- if (options.configType = "PRODUCTION", options.outputDir === "")
1792
+ options.configType = "PRODUCTION", options.configDir = resolve4(options.configDir);
1793
+ let config = await loadMainConfig(options), mainCore = typeof config.core == "object" ? config.core : void 0;
1794
+ options.basePath = resolveBasePath(options.basePath, mainCore?.basePath), options.buildToPublic = options.buildToPublic ?? mainCore?.buildToPublic ?? !1;
1795
+ let outputDir = resolveStaticOutputDir({
1796
+ outputDir: options.outputDir,
1797
+ buildToPublic: options.buildToPublic,
1798
+ basePath: options.basePath
1799
+ });
1800
+ if (outputDir === "")
1337
1801
  throw new Error("Won't remove current directory. Check your outputDir!");
1338
- if (options.outputDir = resolve3(options.outputDir), options.configDir = resolve3(options.configDir), logger4.step(`Cleaning outputDir: ${import_picocolors3.default.cyan(relative3(process.cwd(), options.outputDir))}`), options.outputDir === "/")
1802
+ let outputDirPath = resolve4(outputDir);
1803
+ if (options.outputDir = outputDirPath, logger4.step(`Cleaning outputDir: ${import_picocolors3.default.cyan(relative4(process.cwd(), outputDirPath))}`), outputDirPath === "/")
1339
1804
  throw new Error("Won't remove directory '/'. Check your outputDir!");
1340
- await rm(options.outputDir, { recursive: !0, force: !0 }).catch(() => {
1341
- }), await mkdir(options.outputDir, { recursive: !0 });
1342
- let config = await loadMainConfig(options), { framework } = config, corePresets = [], frameworkName = typeof framework == "string" ? framework : framework?.name;
1343
- frameworkName ? corePresets.push(join4(frameworkName, "preset")) : logger4.warn(`you have not specified a framework in your ${options.configDir}/main.js`);
1344
- let commonPreset = join4(
1805
+ await rm(outputDirPath, { recursive: !0, force: !0 }).catch(() => {
1806
+ }), await mkdir3(outputDirPath, { recursive: !0 });
1807
+ let { framework } = config, corePresets = [], frameworkName = typeof framework == "string" ? framework : framework?.name;
1808
+ frameworkName ? corePresets.push(join6(frameworkName, "preset")) : logger4.warn(`you have not specified a framework in your ${options.configDir}/main.js`);
1809
+ let commonPreset = join6(
1345
1810
  resolvePackageDir("@aussieljk/forkbook"),
1346
1811
  "dist/core-server/presets/common-preset.js"
1347
1812
  ), commonOverridePreset = import.meta.resolve("@aussieljk/forkbook/internal/core-server/presets/common-override-preset");
@@ -1376,7 +1841,7 @@ async function buildStaticStandalone(options) {
1376
1841
  presets.apply("core"),
1377
1842
  presets.apply("staticDirs")
1378
1843
  ]), invokedBy = process.env.FORKBOOK_INVOKED_BY;
1379
- invokedBy && telemetry2("test-run", { runner: invokedBy, watch: !1 }, { configDir: options.configDir });
1844
+ invokedBy && telemetry2("test-run", { runner: invokedBy, watch: !1 });
1380
1845
  let fullOptions = {
1381
1846
  ...options,
1382
1847
  channel,
@@ -1386,20 +1851,21 @@ async function buildStaticStandalone(options) {
1386
1851
  }, effects = [];
1387
1852
  global2.FEATURES = features, await applyServicesPresetOnce(presets), options.previewOnly || await buildOrThrow(
1388
1853
  async () => managerBuilder.build({ startTime: process.hrtime(), options: fullOptions })
1389
- ), staticDirs && effects.push(
1390
- copyAllStaticFilesRelativeToMain(staticDirs, options.outputDir, options.configDir)
1391
- );
1392
- let coreServerPublicDir = join4(resolvePackageDir("@aussieljk/forkbook"), "assets/browser");
1393
- effects.push(cp2(coreServerPublicDir, options.outputDir, { recursive: !0, force: !0 }));
1854
+ ), staticDirs && effects.push(copyAllStaticFilesRelativeToMain(staticDirs, outputDirPath, options.configDir));
1855
+ let coreServerPublicDir = join6(resolvePackageDir("@aussieljk/forkbook"), "assets/browser");
1856
+ effects.push(cp2(coreServerPublicDir, outputDirPath, { recursive: !0, force: !0 }));
1394
1857
  let hasRegisteredServices = getRegisteredServices().length > 0, shouldWriteManifests = features?.componentsManifest;
1395
1858
  (hasRegisteredServices || shouldWriteManifests) && effects.push(
1396
1859
  (async () => {
1397
- hasRegisteredServices && (logger4.info("Building open services.."), await writeOpenServiceStaticFiles(options.outputDir)), shouldWriteManifests && await writeManifests(options.outputDir, presets);
1860
+ hasRegisteredServices && (logger4.info("Building open services.."), await writeOpenServiceStaticFiles(outputDirPath)), shouldWriteManifests && await writeManifests(outputDirPath, presets);
1398
1861
  })()
1399
1862
  );
1400
1863
  let storyIndexGeneratorPromise = presets.apply("storyIndexGenerator");
1401
- effects.push(writeIndexJson(join4(options.outputDir, "index.json"), storyIndexGeneratorPromise)), core?.disableProjectJson || effects.push(
1402
- extractStorybookMetadata(join4(options.outputDir, "project.json"), options.configDir)
1864
+ effects.push(writeIndexJson(join6(outputDirPath, "index.json"), storyIndexGeneratorPromise)), options.previewOnly || effects.push(
1865
+ (async () => {
1866
+ let index = await (await storyIndexGeneratorPromise)?.getIndex();
1867
+ index && (await writeRoutePages(outputDirPath, index), await copyThumbnails(outputDirPath, index, process.cwd()));
1868
+ })()
1403
1869
  ), options.debugWebpack && logConfig("Preview webpack config", await previewBuilder.getConfig(fullOptions)), logger4.info("Building preview..");
1404
1870
  let startTime = process.hrtime();
1405
1871
  if (await Promise.all([
@@ -1409,40 +1875,33 @@ async function buildStaticStandalone(options) {
1409
1875
  }).then(async (previewStats) => {
1410
1876
  logger4.trace({ message: "Preview built", time: process.hrtime(startTime) });
1411
1877
  let statsOption = options.statsJson;
1412
- if (statsOption) {
1413
- let target = statsOption === !0 ? options.outputDir : statsOption;
1414
- await outputStats(target, previewStats);
1415
- }
1878
+ statsOption && await outputStats(statsOption === !0 ? outputDirPath : statsOption, previewStats || void 0);
1416
1879
  }).catch((error) => {
1417
1880
  throw logger4.error("Failed to build the preview"), process.exitCode = 1, error;
1418
1881
  }),
1419
1882
  ...effects
1420
1883
  ]), !options.test)
1421
1884
  try {
1422
- let storyIndex = await (await storyIndexGeneratorPromise)?.getIndex(), payload = {
1423
- precedingUpgrade: await getPrecedingUpgrade()
1424
- };
1425
- storyIndex && Object.assign(payload, {
1426
- storyIndex: summarizeIndex(storyIndex)
1427
- }), await telemetry2("build", payload, { configDir: options.configDir });
1885
+ let storyIndex = await (await storyIndexGeneratorPromise)?.getIndex();
1886
+ await telemetry2("build", storyIndex ? { storyIndex: summarizeIndex(storyIndex) } : {});
1428
1887
  } catch (e) {
1429
1888
  logger4.debug?.(`Build telemetry failed: ${e instanceof Error ? e.message : String(e)}`);
1430
1889
  }
1431
- logger4.step(`Output directory: ${options.outputDir}`);
1890
+ logger4.step(`Output directory: ${outputDirPath}`);
1432
1891
  }
1433
1892
 
1434
1893
  // src/core-server/build-dev.ts
1435
- import { readFile as readFile3 } from "node:fs/promises";
1894
+ import { readFile as readFile5 } from "node:fs/promises";
1436
1895
  import {
1437
1896
  JsPackageManagerFactory,
1438
1897
  getInterpretedFile,
1439
1898
  getProjectRoot,
1440
1899
  isWebContainer,
1441
- defaultConfigDir,
1900
+ defaultConfigDir as defaultConfigDir2,
1442
1901
  loadAllPresets as loadAllPresets2,
1443
1902
  loadMainConfig as loadMainConfig2,
1444
1903
  resolveAddonName as resolveAddonName2,
1445
- resolvePathInStorybookCache as resolvePathInStorybookCache2,
1904
+ resolvePathInForkbookCache as resolvePathInForkbookCache2,
1446
1905
  validateFrameworkName,
1447
1906
  versions
1448
1907
  } from "@aussieljk/forkbook/internal/common";
@@ -1452,8 +1911,7 @@ import {
1452
1911
  NoStatsForViteDevError
1453
1912
  } from "@aussieljk/forkbook/internal/server-errors";
1454
1913
  import { oneWayHash, telemetry as telemetry4 } from "@aussieljk/forkbook/internal/telemetry";
1455
- import { global as global3 } from "@storybook/global";
1456
- import { join as join8, relative as relative4, resolve as resolve6 } from "pathe";
1914
+ import { join as join10, relative as relative5, resolve as resolve7 } from "pathe";
1457
1915
  import { dedent as dedent5 } from "ts-dedent";
1458
1916
 
1459
1917
  // src/channels/postmessage/index.ts
@@ -1525,7 +1983,7 @@ function build_default({ threshold = 1024, level = -1, brotli = !1, gzip = !0, m
1525
1983
 
1526
1984
  // ../../node_modules/polka/build.mjs
1527
1985
  import http from "node:http";
1528
- import { setImmediate } from "node:timers";
1986
+ import { setImmediate as setImmediate2 } from "node:timers";
1529
1987
 
1530
1988
  // ../../node_modules/regexparam/dist/index.mjs
1531
1989
  function parse3(input, loose) {
@@ -1588,7 +2046,7 @@ function onError(err, req, res) {
1588
2046
  }
1589
2047
  var mount = (fn) => fn instanceof Polka ? fn.attach : fn, Polka = class _Polka extends Trouter {
1590
2048
  constructor(opts = {}) {
1591
- super(), this.parse = parse, this.server = opts.server, this.handler = this.handler.bind(this), this.onError = opts.onError || onError, this.onNoMatch = opts.onNoMatch || this.onError.bind(null, { status: 404 }), this.attach = (req, res) => setImmediate(this.handler, req, res);
2049
+ super(), this.parse = parse, this.server = opts.server, this.handler = this.handler.bind(this), this.onError = opts.onError || onError, this.onNoMatch = opts.onNoMatch || this.onError.bind(null, { status: 404 }), this.attach = (req, res) => setImmediate2(this.handler, req, res);
1592
2050
  }
1593
2051
  use(base, ...fns) {
1594
2052
  return base === "/" ? super.use(base, fns.map(mount)) : typeof base == "function" || base instanceof _Polka ? super.use("/", [base, ...fns].map(mount)) : super.use(
@@ -1627,70 +2085,14 @@ function build_default2(opts) {
1627
2085
  }
1628
2086
 
1629
2087
  // src/core-server/change-detection/change-detection-service.ts
1630
- import { join as join5, normalize } from "pathe";
1631
-
1632
- // ../../node_modules/dequal/dist/index.mjs
1633
- var has = Object.prototype.hasOwnProperty;
1634
- function find(iter, tar, key) {
1635
- for (key of iter.keys())
1636
- if (dequal(key, tar)) return key;
1637
- }
1638
- function dequal(foo, bar) {
1639
- var ctor, len, tmp;
1640
- if (foo === bar) return !0;
1641
- if (foo && bar && (ctor = foo.constructor) === bar.constructor) {
1642
- if (ctor === Date) return foo.getTime() === bar.getTime();
1643
- if (ctor === RegExp) return foo.toString() === bar.toString();
1644
- if (ctor === Array) {
1645
- if ((len = foo.length) === bar.length)
1646
- for (; len-- && dequal(foo[len], bar[len]); ) ;
1647
- return len === -1;
1648
- }
1649
- if (ctor === Set) {
1650
- if (foo.size !== bar.size)
1651
- return !1;
1652
- for (len of foo)
1653
- if (tmp = len, tmp && typeof tmp == "object" && (tmp = find(bar, tmp), !tmp) || !bar.has(tmp)) return !1;
1654
- return !0;
1655
- }
1656
- if (ctor === Map) {
1657
- if (foo.size !== bar.size)
1658
- return !1;
1659
- for (len of foo)
1660
- if (tmp = len[0], tmp && typeof tmp == "object" && (tmp = find(bar, tmp), !tmp) || !dequal(len[1], bar.get(tmp)))
1661
- return !1;
1662
- return !0;
1663
- }
1664
- if (ctor === ArrayBuffer)
1665
- foo = new Uint8Array(foo), bar = new Uint8Array(bar);
1666
- else if (ctor === DataView) {
1667
- if ((len = foo.byteLength) === bar.byteLength)
1668
- for (; len-- && foo.getInt8(len) === bar.getInt8(len); ) ;
1669
- return len === -1;
1670
- }
1671
- if (ArrayBuffer.isView(foo)) {
1672
- if ((len = foo.byteLength) === bar.byteLength)
1673
- for (; len-- && foo[len] === bar[len]; ) ;
1674
- return len === -1;
1675
- }
1676
- if (!ctor || typeof foo == "object") {
1677
- len = 0;
1678
- for (ctor in foo)
1679
- if (has.call(foo, ctor) && ++len && !has.call(bar, ctor) || !(ctor in bar) || !dequal(foo[ctor], bar[ctor])) return !1;
1680
- return Object.keys(bar).length === len;
1681
- }
1682
- }
1683
- return foo !== foo && bar !== bar;
1684
- }
1685
-
1686
- // src/core-server/change-detection/change-detection-service.ts
2088
+ import { join as join7, normalize as normalize2 } from "pathe";
1687
2089
  import { logger as logger7 } from "@aussieljk/forkbook/internal/node-logger";
1688
2090
  import { CHANGE_DETECTION_STATUS_TYPE_ID } from "@aussieljk/forkbook/internal/types";
1689
2091
 
1690
2092
  // src/core-server/change-detection/IndexBaselineService.ts
1691
2093
  import {
1692
2094
  createFileSystemCache,
1693
- resolvePathInStorybookCache
2095
+ resolvePathInForkbookCache
1694
2096
  } from "@aussieljk/forkbook/internal/common";
1695
2097
  var DEFAULT_CACHE_KEY = "index-baseline";
1696
2098
  function extractBaselineEntryIds(storyIndex) {
@@ -1705,7 +2107,7 @@ var IndexBaselineService = class {
1705
2107
  this.baselineEntryIds = /* @__PURE__ */ new Set();
1706
2108
  this.syncInFlight = !1;
1707
2109
  this.cache = options.cache ?? createFileSystemCache({
1708
- basePath: resolvePathInStorybookCache(DEFAULT_CACHE_KEY),
2110
+ basePath: resolvePathInForkbookCache(DEFAULT_CACHE_KEY),
1709
2111
  ns: "storybook"
1710
2112
  });
1711
2113
  }
@@ -1755,7 +2157,7 @@ function errorLikeToError(errorLike) {
1755
2157
  return error.name = errorLike.name ?? error.name, errorLike.stack && (error.stack = errorLike.stack), error;
1756
2158
  }
1757
2159
  function isSameStatus(a, b) {
1758
- return a ? a.storyId === b.storyId && a.typeId === b.typeId && a.value === b.value && a.title === b.title && a.description === b.description && a.sidebarContextMenu === b.sidebarContextMenu && dequal(a.data, b.data) : !1;
2160
+ return a ? a.storyId === b.storyId && a.typeId === b.typeId && a.value === b.value && a.title === b.title && a.description === b.description && a.sidebarContextMenu === b.sidebarContextMenu && isEqual(a.data, b.data) : !1;
1759
2161
  }
1760
2162
  function mergeStatusValues(previousValue, nextValue) {
1761
2163
  return previousValue === "status-value:new" || nextValue === "status-value:new" ? "status-value:new" : previousValue === "status-value:modified" || nextValue === "status-value:modified" ? "status-value:modified" : previousValue === "status-value:affected" || nextValue === "status-value:affected" ? "status-value:affected" : nextValue;
@@ -1917,9 +2319,9 @@ var ChangeDetectionService = class {
1917
2319
  this.options.storyIndexGeneratorPromise,
1918
2320
  this.getIndexBaselineService().getBaselineEntryIds()
1919
2321
  ]), changedFiles = new Set(
1920
- Array.from(changes.changed).map((path) => normalize(join5(repoRoot, path)))
2322
+ Array.from(changes.changed).map((path) => normalize2(join7(repoRoot, path)))
1921
2323
  ), newFiles = new Set(
1922
- Array.from(changes.new).map((path) => normalize(join5(repoRoot, path)))
2324
+ Array.from(changes.new).map((path) => normalize2(join7(repoRoot, path)))
1923
2325
  ), scannedFiles = /* @__PURE__ */ new Set([...changedFiles, ...newFiles]), storyIndex = await storyIndexGenerator.getIndex(), baselineStatuses = buildIndexBaselineStatuses(storyIndex, baselineEntryIds), storyIdsByFile = getStoryIdsByAbsolutePath(storyIndex, this.workingDir), statuses = /* @__PURE__ */ new Map(), scannedFilesArray = [...scannedFiles], lookupResults = await this.getModuleGraphIndex().queries.storiesForFiles.loaded({
1924
2326
  files: scannedFilesArray
1925
2327
  });
@@ -1977,8 +2379,114 @@ var ChangeDetectionService = class {
1977
2379
  }
1978
2380
  };
1979
2381
 
2382
+ // src/shared/test-provider-store/index.ts
2383
+ var UNIVERSAL_TEST_PROVIDER_STORE_OPTIONS = {
2384
+ id: "@aussieljk/forkbook/test-provider",
2385
+ leader: !0,
2386
+ initialState: {}
2387
+ };
2388
+ function createTestProviderStore({
2389
+ universalTestProviderStore: universalTestProviderStore2,
2390
+ useUniversalStore
2391
+ }) {
2392
+ let baseStore = {
2393
+ settingsChanged: () => {
2394
+ universalTestProviderStore2.untilReady().then(() => {
2395
+ universalTestProviderStore2.send({ type: "settings-changed" });
2396
+ });
2397
+ },
2398
+ onRunAll: (listener) => universalTestProviderStore2.subscribe("run-all", listener),
2399
+ onClearAll: (listener) => universalTestProviderStore2.subscribe("clear-all", listener)
2400
+ }, fullTestProviderStore2 = {
2401
+ ...baseStore,
2402
+ getFullState: universalTestProviderStore2.getState,
2403
+ setFullState: universalTestProviderStore2.setState,
2404
+ onSettingsChanged: (listener) => universalTestProviderStore2.subscribe("settings-changed", listener),
2405
+ runAll: async () => {
2406
+ await universalTestProviderStore2.untilReady(), universalTestProviderStore2.send({ type: "run-all" });
2407
+ },
2408
+ clearAll: async () => {
2409
+ await universalTestProviderStore2.untilReady(), universalTestProviderStore2.send({ type: "clear-all" });
2410
+ }
2411
+ }, getTestProviderStoreById2 = (testProviderId) => {
2412
+ let getStateForTestProvider = () => universalTestProviderStore2.getState()[testProviderId] ?? "test-provider-state:pending", setStateForTestProvider = (state) => {
2413
+ universalTestProviderStore2.untilReady().then(() => {
2414
+ universalTestProviderStore2.setState((currentState) => ({
2415
+ ...currentState,
2416
+ [testProviderId]: state
2417
+ }));
2418
+ });
2419
+ };
2420
+ return {
2421
+ ...baseStore,
2422
+ testProviderId,
2423
+ getState: getStateForTestProvider,
2424
+ setState: setStateForTestProvider,
2425
+ runWithState: async (callback) => {
2426
+ setStateForTestProvider("test-provider-state:running");
2427
+ try {
2428
+ await callback(), setStateForTestProvider("test-provider-state:succeeded");
2429
+ } catch {
2430
+ setStateForTestProvider("test-provider-state:crashed");
2431
+ }
2432
+ }
2433
+ };
2434
+ };
2435
+ return useUniversalStore ? {
2436
+ getTestProviderStoreById: getTestProviderStoreById2,
2437
+ fullTestProviderStore: fullTestProviderStore2,
2438
+ universalTestProviderStore: universalTestProviderStore2,
2439
+ useTestProviderStore: (selector) => (
2440
+ // The hook also runs without a selector and then returns the whole state.
2441
+ useUniversalStore(
2442
+ universalTestProviderStore2,
2443
+ selector
2444
+ )[0]
2445
+ )
2446
+ } : {
2447
+ getTestProviderStoreById: getTestProviderStoreById2,
2448
+ fullTestProviderStore: fullTestProviderStore2,
2449
+ universalTestProviderStore: universalTestProviderStore2
2450
+ };
2451
+ }
2452
+
2453
+ // src/core-server/stores/test-provider.ts
2454
+ function createServerTestProviderStore(leader) {
2455
+ return createTestProviderStore({
2456
+ universalTestProviderStore: UniversalStore.create({
2457
+ ...UNIVERSAL_TEST_PROVIDER_STORE_OPTIONS,
2458
+ leader
2459
+ })
2460
+ });
2461
+ }
2462
+ var cache = {};
2463
+ function getTestProviderStoreBundle() {
2464
+ return getOrRecreateStore(
2465
+ UNIVERSAL_TEST_PROVIDER_STORE_OPTIONS.id,
2466
+ cache,
2467
+ createServerTestProviderStore
2468
+ );
2469
+ }
2470
+ function startTestProviderStore() {
2471
+ getTestProviderStoreBundle();
2472
+ }
2473
+ var getTestProviderStoreById = (id) => getTestProviderStoreBundle().getTestProviderStoreById(id), fullTestProviderStore = new Proxy(
2474
+ {},
2475
+ {
2476
+ get(_target, prop) {
2477
+ let store = getTestProviderStoreBundle().fullTestProviderStore, value = Reflect.get(store, prop, store);
2478
+ return typeof value == "function" ? value.bind(store) : value;
2479
+ }
2480
+ }
2481
+ ), universalTestProviderStore = new Proxy({}, {
2482
+ get(_target, prop) {
2483
+ let store = getTestProviderStoreBundle().universalTestProviderStore, value = Reflect.get(store, prop, store);
2484
+ return typeof value == "function" ? value.bind(store) : value;
2485
+ }
2486
+ });
2487
+
1980
2488
  // src/core-server/utils/doTelemetry.ts
1981
- import { getPrecedingUpgrade as getPrecedingUpgrade2, telemetry as telemetry3 } from "@aussieljk/forkbook/internal/telemetry";
2489
+ import { telemetry as telemetry3 } from "@aussieljk/forkbook/internal/telemetry";
1982
2490
 
1983
2491
  // src/core-server/utils/versionStatus.ts
1984
2492
  var versionStatus = (versionCheck) => versionCheck.error ? "error" : versionCheck.cached ? "cached" : "success";
@@ -1989,26 +2497,14 @@ async function doTelemetry(app, core, storyIndexGeneratorPromise, options) {
1989
2497
  invariant(
1990
2498
  !versionUpdates || versionUpdates && versionCheck,
1991
2499
  "versionCheck should be defined when versionUpdates is true"
1992
- ), telemetry3(
1993
- "dev",
1994
- async () => {
1995
- let generator = await storyIndexGeneratorPromise, indexAndStats;
1996
- try {
1997
- indexAndStats = await generator?.getIndexAndStats();
1998
- } catch (err) {
1999
- return { error: err instanceof Error ? err : new Error("encountered a non-recoverable error") };
2000
- }
2001
- let payload = {
2002
- precedingUpgrade: await getPrecedingUpgrade2()
2003
- };
2004
- return indexAndStats && Object.assign(payload, {
2005
- versionStatus: versionUpdates && versionCheck ? versionStatus(versionCheck) : "disabled",
2006
- storyIndex: summarizeIndex(indexAndStats.storyIndex),
2007
- storyStats: indexAndStats.stats
2008
- }), payload;
2009
- },
2010
- { configDir: options.configDir }
2011
- );
2500
+ ), telemetry3("dev", async () => {
2501
+ let indexAndStats = await (await storyIndexGeneratorPromise)?.getIndexAndStats();
2502
+ return indexAndStats ? {
2503
+ versionStatus: versionUpdates && versionCheck ? versionStatus(versionCheck) : "disabled",
2504
+ storyIndex: summarizeIndex(indexAndStats.storyIndex),
2505
+ storyStats: indexAndStats.stats
2506
+ } : {};
2507
+ });
2012
2508
  }
2013
2509
 
2014
2510
  // src/core-server/utils/get-caching-middleware.ts
@@ -2055,11 +2551,11 @@ function isHostAllowedInternal(hostHeader, allowedHosts) {
2055
2551
  if (allowedHost === hostname || allowedHost[0] === "." && (allowedHost.slice(1) === hostname || hostname.endsWith(allowedHost))) return !0;
2056
2552
  return !1;
2057
2553
  }
2058
- var cache = /* @__PURE__ */ new WeakMap();
2554
+ var cache2 = /* @__PURE__ */ new WeakMap();
2059
2555
  function isHostAllowed(hostHeader, allowedHosts) {
2060
2556
  if (hostHeader === void 0) return !0;
2061
2557
  let cachedAllowedHosts;
2062
- if (Object.isFrozen(allowedHosts) && (cache.has(allowedHosts) || cache.set(allowedHosts, /* @__PURE__ */ new Set()), cachedAllowedHosts = cache.get(allowedHosts), cachedAllowedHosts.has(hostHeader)))
2558
+ if (Object.isFrozen(allowedHosts) && (cache2.has(allowedHosts) || cache2.set(allowedHosts, /* @__PURE__ */ new Set()), cachedAllowedHosts = cache2.get(allowedHosts), cachedAllowedHosts.has(hostHeader)))
2063
2559
  return !0;
2064
2560
  let result = isHostAllowedInternal(hostHeader, allowedHosts);
2065
2561
  return cachedAllowedHosts && result && cachedAllowedHosts.add(hostHeader), result;
@@ -2130,13 +2626,13 @@ function getSecurityHeadersMiddleware(security) {
2130
2626
 
2131
2627
  // src/core-server/utils/middleware.ts
2132
2628
  import { existsSync } from "node:fs";
2133
- import { resolve as resolve4 } from "pathe";
2629
+ import { resolve as resolve5 } from "pathe";
2134
2630
  var fileExists = (basename4) => [".js", ".mjs", ".cjs"].reduce((found, ext) => {
2135
2631
  let filename = `${basename4}${ext}`;
2136
2632
  return !found && existsSync(filename) ? filename : found;
2137
2633
  }, "");
2138
2634
  async function getMiddleware(configDir) {
2139
- let middlewarePath = fileExists(resolve4(configDir, "middleware"));
2635
+ let middlewarePath = fileExists(resolve5(configDir, "middleware"));
2140
2636
  if (middlewarePath) {
2141
2637
  let middlewareModule = await import("file://" + middlewarePath);
2142
2638
  return middlewareModule.default ?? middlewareModule;
@@ -2153,7 +2649,7 @@ import { dedent } from "ts-dedent";
2153
2649
  // src/core-server/utils/open-browser/opener.ts
2154
2650
  var import_cross_spawn = __toESM(require_cross_spawn(), 1), import_picocolors4 = __toESM(require_picocolors(), 1);
2155
2651
  import { execSync } from "node:child_process";
2156
- import { join as join6 } from "node:path";
2652
+ import { join as join8 } from "node:path";
2157
2653
  import { logger as logger8 } from "@aussieljk/forkbook/internal/node-logger";
2158
2654
  import open from "open";
2159
2655
  var OSX_CHROME = "google chrome";
@@ -2214,7 +2710,7 @@ function startBrowserProcess(browser, url, args) {
2214
2710
  for (let chromiumBrowser of supportedChromiumBrowsers)
2215
2711
  try {
2216
2712
  execSync(`ps cax | grep "${chromiumBrowser}"`);
2217
- let command = `osascript "${join6(
2713
+ let command = `osascript "${join8(
2218
2714
  resolvePackageDir("@aussieljk/forkbook"),
2219
2715
  "assets",
2220
2716
  "server",
@@ -2293,7 +2789,11 @@ Note: BROWSER environment variable is set to "${browserEnv}". To disable browser
2293
2789
  var import_detect_port = __toESM(require_detect_port2(), 1);
2294
2790
  import net3 from "node:net";
2295
2791
  import os2 from "node:os";
2296
- import { SERVER_CHANNEL_PATH as SERVER_CHANNEL_PATH2 } from "@aussieljk/forkbook/internal/channels";
2792
+ import {
2793
+ getChannelPath as getChannelPath2,
2794
+ joinBasePath as joinBasePath2,
2795
+ normalizeBasePath as normalizeBasePath2
2796
+ } from "@aussieljk/forkbook/internal/channels";
2297
2797
  import { logger as logger10 } from "@aussieljk/forkbook/internal/node-logger";
2298
2798
  import { NoFreePortError } from "@aussieljk/forkbook/internal/server-errors";
2299
2799
  var getListenHost = (host) => host || "127.0.0.1", COVERS_LOOPBACK = /* @__PURE__ */ new Set(["127.0.0.1", "0.0.0.0", "::"]), addLoopbackListener = async (server) => {
@@ -2301,30 +2801,32 @@ var getListenHost = (host) => host || "127.0.0.1", COVERS_LOOPBACK = /* @__PURE_
2301
2801
  if (COVERS_LOOPBACK.has(address))
2302
2802
  return;
2303
2803
  let loopback = net3.createServer((socket) => server.emit("connection", socket));
2304
- return server.once("close", () => loopback.close()), await new Promise((resolve9, reject) => {
2305
- loopback.once("error", reject), loopback.listen({ port, host: "127.0.0.1" }, resolve9);
2804
+ return server.once("close", () => loopback.close()), await new Promise((resolve10, reject) => {
2805
+ loopback.once("error", reject), loopback.listen({ port, host: "127.0.0.1" }, resolve10);
2306
2806
  }), loopback;
2307
2807
  };
2308
2808
  function getServerAddresses(port, host, proto, initialPath) {
2309
2809
  let address = new URL(`${proto}://127.0.0.1:${port}/`), networkAddress = new URL(`${proto}://${host || getLocalIp()}:${port}/`);
2310
- if (initialPath) {
2311
- let searchParams = `?path=${decodeURIComponent(
2312
- initialPath.startsWith("/") ? initialPath : `/${initialPath}`
2313
- )}`;
2314
- address.search = searchParams, networkAddress.search = searchParams;
2315
- }
2316
2810
  return {
2317
- address: address.href,
2318
- networkAddress: networkAddress.href
2811
+ address: withInitialPath(address.href, initialPath),
2812
+ networkAddress: withInitialPath(networkAddress.href, initialPath)
2319
2813
  };
2320
2814
  }
2815
+ function withInitialPath(address, initialPath, basePath) {
2816
+ if (!initialPath && !basePath)
2817
+ return address;
2818
+ let url = new URL(address);
2819
+ return initialPath && (url.pathname = decodeURIComponent(
2820
+ initialPath.startsWith("/") ? initialPath : `/${initialPath}`
2821
+ ).replace(/^\/(story|docs)\//, "/_$1/")), basePath && (url.pathname = joinBasePath2(basePath, url.pathname)), url.href;
2822
+ }
2321
2823
  var getServerPort = (port, { exactPort } = {}) => (0, import_detect_port.default)(port).catch((error) => {
2322
2824
  logger10.error(error), process.exit(-1);
2323
2825
  }).then((freePort) => {
2324
2826
  if (!freePort)
2325
2827
  throw new NoFreePortError({ requestedPort: port });
2326
2828
  return exactPort && port != null && freePort !== port && (logger10.error(`Port ${port} is not available. Exiting because --exact-port was provided.`), process.exit(-1)), freePort;
2327
- }), getServerChannelUrl = (port, { https: https2 }) => `${https2 ? "wss" : "ws"}://127.0.0.1:${port}${SERVER_CHANNEL_PATH2}`, getExternalIpv4Addresses = () => Object.values(os2.networkInterfaces()).flat().filter((ip) => ip && ip.family === "IPv4" && !ip.internal).map((ip) => ip.address), getLocalIp = () => getExternalIpv4Addresses()[0] ?? "0.0.0.0", getReachableNetworkAddresses = (networkAddress) => {
2829
+ }), getServerChannelUrl = (port, { https: https2, basePath }) => `${https2 ? "wss" : "ws"}://127.0.0.1:${port}${getChannelPath2(normalizeBasePath2(basePath))}`, getExternalIpv4Addresses = () => Object.values(os2.networkInterfaces()).flat().filter((ip) => ip && ip.family === "IPv4" && !ip.internal).map((ip) => ip.address), getLocalIp = () => getExternalIpv4Addresses()[0] ?? "0.0.0.0", getReachableNetworkAddresses = (networkAddress) => {
2328
2830
  if (new URL(networkAddress).hostname !== "0.0.0.0")
2329
2831
  return [networkAddress];
2330
2832
  let addresses = getExternalIpv4Addresses().map((ip) => {
@@ -2336,10 +2838,16 @@ var getServerPort = (port, { exactPort } = {}) => (0, import_detect_port.default
2336
2838
 
2337
2839
  // src/core-server/dev-server.ts
2338
2840
  async function storybookDevServer(options, server) {
2339
- let core = await options.presets.apply("core"), security = await options.presets.apply("security"), app = build_default2({ server }), workingDir = process.cwd(), configDir = options.configDir, features = await options.presets.apply("features"), stories = await options.presets.apply("stories"), normalizedStories = normalizeStories(stories, {
2841
+ let core = await options.presets.apply("core"), security = await options.presets.apply("security"), app = build_default2({ server }), basePath = normalizeBasePath(options.basePath), mountBasePath = createBasePathMount(basePath), handle = app.handler;
2842
+ app.attach = (req, res) => {
2843
+ mountBasePath(req, res) || setImmediate(handle, req, res);
2844
+ };
2845
+ let workingDir = process.cwd(), configDir = options.configDir, features = await options.presets.apply("features"), stories = await options.presets.apply("stories"), normalizedStories = normalizeStories(stories, {
2340
2846
  configDir,
2341
2847
  workingDir
2342
- }), storyIndexGeneratorPromise = withSpan(
2848
+ });
2849
+ startTestProviderStore();
2850
+ let storyIndexGeneratorPromise = withSpan(
2343
2851
  "forkbook.story-index",
2344
2852
  {},
2345
2853
  () => options.presets.apply("storyIndexGenerator")
@@ -2365,15 +2873,23 @@ async function storybookDevServer(options, server) {
2365
2873
  channel: options.channel,
2366
2874
  workingDir,
2367
2875
  configDir
2368
- }), (await getMiddleware(options.configDir))(app), await options.presets.apply("experimental_devServer", app), !core?.builder)
2876
+ }), registerThumbnailRoute(app, workingDir), (await getMiddleware(options.configDir))(app), await options.presets.apply("experimental_devServer", app), !core?.builder)
2369
2877
  throw new MissingBuilderError();
2370
2878
  let resolvedPreviewBuilder = typeof core?.builder == "string" ? core.builder : core?.builder?.name, [previewBuilder, managerBuilder] = await Promise.all([
2371
2879
  getPreviewBuilder(resolvedPreviewBuilder),
2372
2880
  getManagerBuilder(),
2373
2881
  useStatics(app, options)
2374
- ]);
2375
- options.debugWebpack && logConfig2("Preview webpack config", await previewBuilder.getConfig(options)), core?.disableProjectJson || useStorybookMetadata(app, options.configDir);
2376
- let managerResult = options.previewOnly ? void 0 : await withSpan(
2882
+ ]), listening = new Promise((resolve10, reject) => {
2883
+ server.once("error", reject), app.listen({ port: options.port, host: getListenHost(options.host) }, resolve10);
2884
+ }).then(() => addLoopbackListener(server));
2885
+ listening.catch(() => {
2886
+ }), storyIndexGeneratorPromise.then((generator) => generator?.getIndex()).catch(() => {
2887
+ }), options.debugWebpack && logConfig2("Preview webpack config", await previewBuilder.getConfig(options));
2888
+ let bailBuilders = async () => {
2889
+ await disposeChangeDetectionRuntime(), await managerBuilder?.bail().catch(() => {
2890
+ }), await previewBuilder?.bail().catch(() => {
2891
+ });
2892
+ }, managerPromise = options.previewOnly ? Promise.resolve(void 0) : withSpan(
2377
2893
  "forkbook.manager-start",
2378
2894
  {},
2379
2895
  () => managerBuilder.start({
@@ -2383,8 +2899,9 @@ async function storybookDevServer(options, server) {
2383
2899
  server,
2384
2900
  channel: options.channel
2385
2901
  })
2386
- ), previewResult = await Promise.resolve();
2387
- logger11.debug("Starting preview.."), previewResult = await withSpan(
2902
+ );
2903
+ logger11.debug("Starting preview..");
2904
+ let previewPromise = withSpan(
2388
2905
  "forkbook.preview-start",
2389
2906
  {},
2390
2907
  () => previewBuilder.start({
@@ -2393,12 +2910,15 @@ async function storybookDevServer(options, server) {
2393
2910
  router: app,
2394
2911
  server,
2395
2912
  channel: options.channel
2396
- }).catch(async (e) => {
2397
- throw logger11.error("Failed to build the preview"), process.exitCode = 1, await disposeChangeDetectionRuntime(), await managerBuilder?.bail().catch(() => {
2398
- }), await previewBuilder?.bail().catch(() => {
2399
- }), e;
2400
2913
  })
2401
- );
2914
+ ).catch((e) => {
2915
+ throw logger11.error("Failed to build the preview"), process.exitCode = 1, e;
2916
+ }), managerResult, previewResult;
2917
+ try {
2918
+ [managerResult, previewResult] = await Promise.all([managerPromise, previewPromise]);
2919
+ } catch (e) {
2920
+ throw await bailBuilders(), e;
2921
+ }
2402
2922
  let adapter;
2403
2923
  try {
2404
2924
  adapter = previewBuilder.changeDetectionAdapter?.();
@@ -2406,20 +2926,17 @@ async function storybookDevServer(options, server) {
2406
2926
  logger11.warn("Change detection: adapter initialisation failed"), logger11.debug(err instanceof Error ? err.stack ?? err.message : String(err));
2407
2927
  }
2408
2928
  resolveChangeDetectionAdapter(adapter), changeDetectionService.start();
2409
- let listening = new Promise((resolve9, reject) => {
2410
- server.once("error", reject), app.listen({ port: options.port, host: getListenHost(options.host) }, resolve9);
2411
- }).then(() => addLoopbackListener(server));
2412
2929
  try {
2413
2930
  let [indexGenerator] = await Promise.all([storyIndexGeneratorPromise, listening]);
2414
2931
  if (indexGenerator && !options.ci && !options.smokeTest && options.open) {
2415
2932
  let url = options.host && options.host !== "0.0.0.0" ? options.networkAddress : options.localAddress;
2416
- openInBrowser(options.previewOnly ? `${url}iframe.html?navigator=true` : url).catch(() => {
2933
+ openInBrowser(
2934
+ options.previewOnly ? `${withInitialPath(url, "/iframe.html", basePath)}?navigator=true` : withInitialPath(url, options.initialPath, basePath)
2935
+ ).catch(() => {
2417
2936
  });
2418
2937
  }
2419
2938
  } catch (e) {
2420
- throw await disposeChangeDetectionRuntime(), await managerBuilder?.bail().catch(() => {
2421
- }), await previewBuilder?.bail().catch(() => {
2422
- }), e;
2939
+ throw await bailBuilders(), e;
2423
2940
  }
2424
2941
  features?.componentsManifest && registerManifests({ app, presets: options.presets }), doTelemetry(app, core, storyIndexGeneratorPromise, options);
2425
2942
  async function cancelTelemetry() {
@@ -2435,7 +2952,7 @@ async function storybookDevServer(options, server) {
2435
2952
  });
2436
2953
  } catch {
2437
2954
  }
2438
- await telemetry("canceled", payload, { immediate: !0 });
2955
+ await telemetry("canceled", payload);
2439
2956
  } finally {
2440
2957
  await disposeChangeDetectionRuntime(), process.exit(0);
2441
2958
  }
@@ -2448,7 +2965,8 @@ var import_telejson2 = __toESM(require_dist(), 1);
2448
2965
  import {
2449
2966
  Channel as Channel3,
2450
2967
  HEARTBEAT_INTERVAL as HEARTBEAT_INTERVAL2,
2451
- SERVER_CHANNEL_PATH as SERVER_CHANNEL_PATH3,
2968
+ getChannelPath as getChannelPath3,
2969
+ normalizeBasePath as normalizeBasePath3,
2452
2970
  setChannel as setChannel2
2453
2971
  } from "@aussieljk/forkbook/internal/channels";
2454
2972
  import { WebSocket, WebSocketServer } from "ws";
@@ -2457,6 +2975,7 @@ import { WebSocket, WebSocketServer } from "ws";
2457
2975
  import events from "@aussieljk/forkbook/internal/core-events";
2458
2976
  var CORE_EVENT_SENDERS = {
2459
2977
  [events.CHANNEL_WS_DISCONNECT]: "any",
2978
+ [events.CHANNEL_WS_RECONNECT]: "any",
2460
2979
  [events.CHANNEL_CREATED]: "manager",
2461
2980
  [events.CONFIG_ERROR]: "preview",
2462
2981
  [events.STORY_INDEX_INVALIDATED]: "server",
@@ -2497,6 +3016,7 @@ var CORE_EVENT_SENDERS = {
2497
3016
  [events.STORIES_COLLAPSE_ALL]: "manager",
2498
3017
  [events.STORIES_EXPAND_ALL]: "manager",
2499
3018
  [events.DOCS_RENDERED]: "preview",
3019
+ [events.DOCS_PAGE_IN_VIEW]: "preview",
2500
3020
  [events.SHARED_STATE_CHANGED]: "any",
2501
3021
  [events.SHARED_STATE_SET]: "any",
2502
3022
  [events.NAVIGATE_URL]: "any",
@@ -2510,8 +3030,6 @@ var CORE_EVENT_SENDERS = {
2510
3030
  [events.SAVE_STORY_RESPONSE]: "server",
2511
3031
  [events.ARGTYPES_INFO_REQUEST]: "manager",
2512
3032
  [events.ARGTYPES_INFO_RESPONSE]: "preview",
2513
- [events.GHOST_STORIES_REQUEST]: "manager",
2514
- [events.GHOST_STORIES_RESPONSE]: "server",
2515
3033
  [events.AI_SETUP_ANALYTICS_RESPONSE]: "server",
2516
3034
  [events.AI_SETUP_ANALYTICS_REQUEST]: "server",
2517
3035
  [events.OPEN_IN_EDITOR_REQUEST]: "manager",
@@ -2545,14 +3063,16 @@ var ServerChannelTransport = class {
2545
3063
  }), this.socket.close(() => process.exit(0));
2546
3064
  };
2547
3065
  this.rejectedEvents = /* @__PURE__ */ new Set();
2548
- this.socket = new WebSocketServer({ noServer: !0 }), server.on("upgrade", (request, socket, head) => {
3066
+ this.socket = new WebSocketServer({ noServer: !0 });
3067
+ let channelPath = getChannelPath3(normalizeBasePath3(options.basePath));
3068
+ server.on("upgrade", (request, socket, head) => {
2549
3069
  try {
2550
3070
  let url = request.url && new URL(request.url, options.localAddress);
2551
- if (!url || url.pathname !== SERVER_CHANNEL_PATH3)
3071
+ if (!url || url.pathname !== channelPath)
2552
3072
  return;
2553
3073
  if (!options.skipValidation) {
2554
- let { origin } = request.headers;
2555
- if (origin && !isValidHost(new URL(origin).host, options)) {
3074
+ let { origin } = request.headers, originHost = origin ? new URL(origin).host : void 0;
3075
+ if (originHost && !isValidHost(originHost, options) && !isForwardedForOrigin(request, originHost)) {
2556
3076
  socket.end(`HTTP/1.1 403 Forbidden\r
2557
3077
  Connection: close\r
2558
3078
  \r
@@ -2642,10 +3162,10 @@ function prepareHeadlessUniversalStores() {
2642
3162
  }
2643
3163
 
2644
3164
  // src/core-server/utils/host-validation-warning.ts
2645
- import { cache as cache2, isCI } from "@aussieljk/forkbook/internal/common";
3165
+ import { cache as cache3, isCI } from "@aussieljk/forkbook/internal/common";
2646
3166
  import { logger as logger12, prompt } from "@aussieljk/forkbook/internal/node-logger";
2647
3167
  import { dedent as dedent2 } from "ts-dedent";
2648
- var DOCS_URL = "https://storybook.js.org/docs/api/main-config/main-config-core#allowedhosts", getHostValidationWarning = ({
3168
+ var DOCS_URL = "https://forkbook.ljk.dev/docs/api/main-config/main-config-core#allowedhosts", getHostValidationWarning = ({
2649
3169
  host,
2650
3170
  allowedHosts
2651
3171
  }) => {
@@ -2678,7 +3198,7 @@ async function warnOnDisabledHostValidation(options) {
2678
3198
  if (!warning || (logger12.warn(warning.message), options.ci || options.smokeTest || !isInteractiveTerminal()))
2679
3199
  return;
2680
3200
  let skipPromptKey = `host-validation-prompt-skipped-${warning.id}-${options.cacheKey}`;
2681
- if (await cache2.get(skipPromptKey).catch(() => !1))
3201
+ if (await cache3.get(skipPromptKey).catch(() => !1))
2682
3202
  return;
2683
3203
  let choice = await prompt.select({
2684
3204
  message: "How do you want to proceed?",
@@ -2697,54 +3217,55 @@ async function warnOnDisabledHostValidation(options) {
2697
3217
  ],
2698
3218
  initialValue: "continue"
2699
3219
  });
2700
- choice === "abort" && process.exit(1), choice === "dont-ask" && await cache2.set(skipPromptKey, !0).catch(() => {
3220
+ choice === "abort" && process.exit(1), choice === "dont-ask" && await cache3.set(skipPromptKey, !0).catch(() => {
2701
3221
  });
2702
3222
  }
2703
3223
 
2704
3224
  // src/core-server/utils/output-startup-information.ts
2705
- var import_picocolors6 = __toESM(require_picocolors(), 1), import_pretty_hrtime = __toESM(require_pretty_hrtime(), 1);
2706
- import { CLI_COLORS, logger as logger13 } from "@aussieljk/forkbook/internal/node-logger";
3225
+ var import_picocolors6 = __toESM(require_picocolors(), 1);
3226
+ import { CLI_COLORS, logger as logger13, prettyTime } from "@aussieljk/forkbook/internal/node-logger";
2707
3227
  import { dedent as dedent4 } from "ts-dedent";
2708
3228
 
2709
3229
  // src/core-server/utils/update-check.ts
2710
3230
  var import_picocolors5 = __toESM(require_picocolors(), 1);
2711
- import { cache as cache3 } from "@aussieljk/forkbook/internal/common";
3231
+ import { cache as cache4 } from "@aussieljk/forkbook/internal/common";
2712
3232
  import { colors } from "@aussieljk/forkbook/internal/node-logger";
2713
3233
  import semver from "semver";
2714
3234
  import { dedent as dedent3 } from "ts-dedent";
2715
- var { FORKBOOK_VERSION_BASE = "https://storybook.js.org", CI } = process.env, updateCheck = async (version) => {
3235
+ var { FORKBOOK_VERSION_BASE = "https://forkbook.ljk.dev", CI } = process.env, updateCheck = async (version) => {
2716
3236
  let result, time = Date.now();
2717
3237
  try {
2718
- let fromCache = await cache3.get("lastUpdateCheck", { success: !1, time: 0 });
3238
+ let fromCache = await cache4.get("lastUpdateCheck", { success: !1, time: 0 });
2719
3239
  time - 864e5 > fromCache.time && !CI ? (result = { success: !0, cached: !1, data: await (await Promise.race([
2720
3240
  fetch(`${FORKBOOK_VERSION_BASE}/versions.json?current=${version}`),
2721
3241
  // if fetch is too slow, we won't wait for it
2722
3242
  new Promise((res, rej) => global.setTimeout(rej, 1500))
2723
- ])).json(), time }, await cache3.set("lastUpdateCheck", result)) : result = { ...fromCache, cached: !0 };
3243
+ ])).json(), time }, await cache4.set("lastUpdateCheck", result)) : result = { ...fromCache, cached: !0 };
2724
3244
  } catch (error) {
2725
3245
  result = { success: !1, cached: !1, error, time };
2726
3246
  }
2727
3247
  return result;
2728
3248
  };
2729
3249
  function createUpdateMessage(updateInfo, version) {
2730
- let updateMessage;
3250
+ let latestVersion = updateInfo.data?.latest?.version;
3251
+ if (!updateInfo.success || !latestVersion)
3252
+ return "";
2731
3253
  try {
2732
- let upgradeCommand = `npx storybook@${semver.prerelease(updateInfo.data.latest.version) ? "next" : "latest"} upgrade`;
2733
- updateMessage = updateInfo.success && semver.lt(version, updateInfo.data.latest.version) ? dedent3`
2734
- ${colors.orange(
2735
- `A new version (${import_picocolors5.default.bold(updateInfo.data.latest.version)}) is available!`
2736
- )}
3254
+ if (!semver.lt(version, latestVersion))
3255
+ return "";
3256
+ let upgradeCommand = `npx @aussieljk/forkbook@${semver.prerelease(latestVersion) ? "next" : "latest"} upgrade`;
3257
+ return dedent3`
3258
+ ${colors.orange(`A new version (${import_picocolors5.default.bold(latestVersion)}) is available!`)}
2737
3259
 
2738
- ${import_picocolors5.default.gray("Upgrade now:")} ${colors.green(upgradeCommand)}
3260
+ ${import_picocolors5.default.gray("Upgrade now:")} ${colors.green(upgradeCommand)}
2739
3261
 
2740
- ${import_picocolors5.default.gray("Read full changelog:")} ${import_picocolors5.default.gray(
2741
- import_picocolors5.default.underline("https://github.com/storybookjs/storybook/blob/main/CHANGELOG.md")
3262
+ ${import_picocolors5.default.gray("Read full changelog:")} ${import_picocolors5.default.gray(
3263
+ import_picocolors5.default.underline("https://github.com/aussieljk/forkbook/commits/master")
2742
3264
  )}
2743
- ` : "";
3265
+ `;
2744
3266
  } catch {
2745
- updateMessage = "";
3267
+ return "";
2746
3268
  }
2747
- return updateMessage;
2748
3269
  }
2749
3270
 
2750
3271
  // src/core-server/utils/output-startup-information.ts
@@ -2781,8 +3302,8 @@ ${updateMessage}` : ""}
2781
3302
  }
2782
3303
  );
2783
3304
  let timeStatement = [
2784
- managerTotalTime && `${import_picocolors6.default.underline((0, import_pretty_hrtime.default)(managerTotalTime))} for manager`,
2785
- previewTotalTime && `${import_picocolors6.default.underline((0, import_pretty_hrtime.default)(previewTotalTime))} for preview`
3305
+ managerTotalTime && `${import_picocolors6.default.underline(prettyTime(managerTotalTime))} for manager`,
3306
+ previewTotalTime && `${import_picocolors6.default.underline(prettyTime(previewTotalTime))} for preview`
2786
3307
  ].filter(Boolean).join(" and ");
2787
3308
  logger13.info(timeStatement);
2788
3309
  }
@@ -2791,10 +3312,10 @@ ${updateMessage}` : ""}
2791
3312
  import { execFile } from "node:child_process";
2792
3313
  import { randomUUID } from "node:crypto";
2793
3314
  import { existsSync as existsSync2, rmSync } from "node:fs";
2794
- import { chmod, mkdir as mkdir2, readFile, readdir, rename, rm as rm2, stat, writeFile as writeFile3 } from "node:fs/promises";
3315
+ import { chmod, mkdir as mkdir4, readFile as readFile3, readdir, rename, rm as rm2, stat, writeFile as writeFile3 } from "node:fs/promises";
2795
3316
  import { homedir, userInfo } from "node:os";
2796
3317
  import { findStorybookPackageRoot, normalizeAddonName } from "@aussieljk/forkbook/internal/common";
2797
- import { join as join7, resolve as resolve5 } from "pathe";
3318
+ import { join as join9, resolve as resolve6 } from "pathe";
2798
3319
  var FORKBOOK_MCP_ADDON = "@aussieljk/forkbook/addon-mcp", DEFAULT_MCP_ENDPOINT = "/mcp", ONE_DAY_MS = 1440 * 60 * 1e3, SEVEN_DAYS_MS = 7 * ONE_DAY_MS, REGISTRY_DIR_MODE = 448, RECORD_FILE_MODE = 384;
2799
3320
  function execFileAsync(file, args) {
2800
3321
  return new Promise((resolveExec, rejectExec) => {
@@ -2821,7 +3342,7 @@ async function restrictOwnerAccess(targetPath, mode) {
2821
3342
  }
2822
3343
  }
2823
3344
  function getDefaultRuntimeInstanceRegistryDir() {
2824
- return join7(homedir(), ".forkbook", "instances");
3345
+ return join9(homedir(), ".forkbook", "instances");
2825
3346
  }
2826
3347
  function getStorybookBaseUrl(address) {
2827
3348
  let url = new URL(address);
@@ -2855,8 +3376,8 @@ function createRuntimeInstanceRecord({
2855
3376
  schemaVersion: 1,
2856
3377
  instanceId,
2857
3378
  pid,
2858
- cwd: resolve5(cwd),
2859
- ...configDir ? { configDir: resolve5(cwd, configDir) } : {},
3379
+ cwd: resolve6(cwd),
3380
+ ...configDir ? { configDir: resolve6(cwd, configDir) } : {},
2860
3381
  url: storybookBaseUrl,
2861
3382
  port,
2862
3383
  ...token ? { token } : {},
@@ -2869,8 +3390,8 @@ function createRuntimeInstanceRecord({
2869
3390
  };
2870
3391
  }
2871
3392
  async function writeRuntimeInstanceRecord(record, registryDir = getDefaultRuntimeInstanceRegistryDir()) {
2872
- await mkdir2(registryDir, { recursive: !0, mode: REGISTRY_DIR_MODE }), await restrictOwnerAccess(registryDir, REGISTRY_DIR_MODE), await cleanupRuntimeInstanceRegistry(registryDir);
2873
- let recordPath = join7(registryDir, `${record.instanceId}.json`), tempPath = join7(
3393
+ await mkdir4(registryDir, { recursive: !0, mode: REGISTRY_DIR_MODE }), await restrictOwnerAccess(registryDir, REGISTRY_DIR_MODE), await cleanupRuntimeInstanceRegistry(registryDir);
3394
+ let recordPath = join9(registryDir, `${record.instanceId}.json`), tempPath = join9(
2874
3395
  registryDir,
2875
3396
  `${record.instanceId}.${record.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`
2876
3397
  );
@@ -2936,7 +3457,7 @@ async function cleanupRuntimeInstanceRegistry(registryDir) {
2936
3457
  entries.map(async (entry) => {
2937
3458
  if (!entry.isFile())
2938
3459
  return;
2939
- let recordPath = join7(registryDir, entry.name);
3460
+ let recordPath = join9(registryDir, entry.name);
2940
3461
  try {
2941
3462
  let { mtimeMs } = await stat(recordPath);
2942
3463
  if (entry.name.endsWith(".tmp")) {
@@ -2952,7 +3473,7 @@ async function cleanupRuntimeInstanceRegistry(registryDir) {
2952
3473
  }
2953
3474
  if (!entry.name.endsWith(".json"))
2954
3475
  return;
2955
- let content = await readFile(recordPath, "utf-8"), record;
3476
+ let content = await readFile3(recordPath, "utf-8"), record;
2956
3477
  try {
2957
3478
  record = JSON.parse(content);
2958
3479
  } catch {
@@ -3024,7 +3545,7 @@ async function writeStorybookRuntimeInstanceRecord({
3024
3545
  }
3025
3546
 
3026
3547
  // src/core-server/utils/server-init.ts
3027
- import { readFile as readFile2 } from "node:fs/promises";
3548
+ import { readFile as readFile4 } from "node:fs/promises";
3028
3549
  import { logger as logger14 } from "@aussieljk/forkbook/internal/node-logger";
3029
3550
  import http2 from "http";
3030
3551
  import https from "https";
@@ -3033,9 +3554,9 @@ async function getServer(options) {
3033
3554
  return http2.createServer();
3034
3555
  options.sslCert || (logger14.error("Error: --ssl-cert is required with --https"), process.exit(-1)), options.sslKey || (logger14.error("Error: --ssl-key is required with --https"), process.exit(-1));
3035
3556
  let sslOptions = {
3036
- ca: await Promise.all((options.sslCa || []).map((ca) => readFile2(ca, { encoding: "utf8" }))),
3037
- cert: await readFile2(options.sslCert, { encoding: "utf8" }),
3038
- key: await readFile2(options.sslKey, { encoding: "utf8" })
3557
+ ca: await Promise.all((options.sslCa || []).map((ca) => readFile4(ca, { encoding: "utf8" }))),
3558
+ cert: await readFile4(options.sslCert, { encoding: "utf8" }),
3559
+ key: await readFile4(options.sslKey, { encoding: "utf8" })
3039
3560
  };
3040
3561
  return https.createServer(sslOptions);
3041
3562
  }
@@ -3050,7 +3571,7 @@ function stripCommentsAndStrings(code) {
3050
3571
 
3051
3572
  // src/core-server/build-dev.ts
3052
3573
  async function buildDevStandalone(options) {
3053
- let { packageJson, versionUpdates } = options, { storybookVersion } = options, configDir = resolve6(options.configDir);
3574
+ let { packageJson, versionUpdates } = options, { storybookVersion } = options, configDir = resolve7(options.configDir);
3054
3575
  packageJson ? (invariant(
3055
3576
  packageJson.version !== void 0,
3056
3577
  `Expected package.json#version to be defined in the "${packageJson.name}" package}`
@@ -3066,17 +3587,26 @@ async function buildDevStandalone(options) {
3066
3587
  `,
3067
3588
  initialValue: !0
3068
3589
  }) || process.exit(1));
3069
- let cacheKey = oneWayHash(relative4(getProjectRoot(), configDir));
3590
+ let cacheKey = oneWayHash(relative5(getProjectRoot(), configDir));
3070
3591
  invariant(port, "expected options to have a port");
3071
3592
  let { address: localAddress, networkAddress } = getServerAddresses(
3072
3593
  port,
3073
3594
  options.host,
3074
- options.https ? "https" : "http",
3075
- options.initialPath
3076
- ), cacheOutputDir = resolvePathInStorybookCache2("public", cacheKey), outputDir = resolve6(options.outputDir || cacheOutputDir);
3077
- options.smokeTest && (outputDir = cacheOutputDir), options.port = port, options.versionCheck = versionCheck, options.configType = "DEVELOPMENT", options.configDir = configDir, options.cacheKey = cacheKey, options.outputDir = outputDir, options.serverChannelUrl = getServerChannelUrl(port, options), options.localAddress = localAddress, options.networkAddress = networkAddress;
3078
- let config = await loadMainConfig2(options), { core, framework } = config, corePresets = [], frameworkName = typeof framework == "string" ? framework : framework?.name;
3079
- validateFrameworkName(frameworkName), frameworkName && corePresets.push(join8(frameworkName, "preset")), frameworkName = frameworkName || "custom";
3595
+ options.https ? "https" : "http"
3596
+ ), cacheOutputDir = resolvePathInForkbookCache2("public", cacheKey), outputDir = resolve7(options.outputDir || cacheOutputDir);
3597
+ options.smokeTest && (outputDir = cacheOutputDir), options.port = port, options.versionCheck = versionCheck, options.configType = "DEVELOPMENT", options.configDir = configDir, options.cacheKey = cacheKey, options.outputDir = outputDir, options.localAddress = localAddress, options.networkAddress = networkAddress;
3598
+ let config = await loadMainConfig2(options), { core, framework } = config;
3599
+ options.basePath = resolveBasePath(
3600
+ options.basePath,
3601
+ typeof core == "object" ? core.basePath : void 0
3602
+ ), options.serverChannelUrl = getServerChannelUrl(port, options), watchParentProcess();
3603
+ let corePresets = [], frameworkName = typeof framework == "string" ? framework : framework?.name;
3604
+ validateFrameworkName(frameworkName), frameworkName && corePresets.push(join10(frameworkName, "preset")), (config.addons ?? []).some(
3605
+ (addon) => (typeof addon == "string" ? addon : addon.name).includes("addon-comments")
3606
+ ) || corePresets.push({
3607
+ name: "@aussieljk/forkbook/addon-comments/preset",
3608
+ options: { forkbookDefaultComments: !0 }
3609
+ }), frameworkName = frameworkName || "custom";
3080
3610
  let packageManager = JsPackageManagerFactory.getPackageManager({
3081
3611
  configDir: options.configDir
3082
3612
  }), server = await getServer(options), presets = await loadAllPresets2({
@@ -3110,11 +3640,11 @@ async function buildDevStandalone(options) {
3110
3640
  ]);
3111
3641
  if (resolvedPreviewBuilder.includes("builder-vite")) {
3112
3642
  let deprecationMessage = dedent5(`Using CommonJS in your main configuration file is deprecated with Vite.
3113
- - Refer to the migration guide at https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#commonjs-with-vite-is-deprecated`), mainJsPath = getInterpretedFile(
3114
- resolve6(options.configDir || defaultConfigDir(), "main")
3643
+ - Refer to the migration guide at https://forkbook.ljk.dev/docs/migration#commonjs-with-vite-is-deprecated`), mainJsPath = getInterpretedFile(
3644
+ resolve7(options.configDir || defaultConfigDir2(), "main")
3115
3645
  );
3116
3646
  /\.c[jt]s$/.test(mainJsPath) && deprecate(deprecationMessage);
3117
- let mainJsContent = await readFile3(mainJsPath, { encoding: "utf8" }), CJS_CONTENT_REGEX = /\bmodule\.exports\b|\bexports[.[]|\brequire\s*\(|\bObject\.(?:defineProperty|defineProperties|assign)\s*\(\s*exports\b/, strippedContent = stripCommentsAndStrings(mainJsContent);
3647
+ let mainJsContent = await readFile5(mainJsPath, { encoding: "utf8" }), CJS_CONTENT_REGEX = /\bmodule\.exports\b|\bexports[.[]|\brequire\s*\(|\bObject\.(?:defineProperty|defineProperties|assign)\s*\(\s*exports\b/, strippedContent = stripCommentsAndStrings(mainJsContent);
3118
3648
  CJS_CONTENT_REGEX.test(strippedContent) && deprecate(deprecationMessage);
3119
3649
  }
3120
3650
  let resolvedRenderer = renderer && resolveAddonName2(options.configDir, renderer, options), channel = getServerChannel(server, {
@@ -3123,11 +3653,12 @@ async function buildDevStandalone(options) {
3123
3653
  allowedHosts,
3124
3654
  skipValidation: isWebContainer(),
3125
3655
  localAddress,
3126
- networkAddress
3656
+ networkAddress,
3657
+ basePath: options.basePath
3127
3658
  });
3128
3659
  presets = await loadAllPresets2({
3129
3660
  corePresets: [
3130
- join8(resolvePackageDir("@aussieljk/forkbook"), "dist/core-server/presets/common-preset.js"),
3661
+ join10(resolvePackageDir("@aussieljk/forkbook"), "dist/core-server/presets/common-preset.js"),
3131
3662
  ...managerBuilder.corePresets || [],
3132
3663
  ...previewBuilder.corePresets || [],
3133
3664
  ...resolvedRenderer ? [resolvedRenderer] : [],
@@ -3141,7 +3672,7 @@ async function buildDevStandalone(options) {
3141
3672
  channel
3142
3673
  });
3143
3674
  let features = await presets.apply("features");
3144
- global3.FEATURES = features, await presets.apply("experimental_serverChannel", channel);
3675
+ global2.FEATURES = features, await presets.apply("experimental_serverChannel", channel);
3145
3676
  let fullOptions = {
3146
3677
  ...options,
3147
3678
  presets,
@@ -3151,7 +3682,7 @@ async function buildDevStandalone(options) {
3151
3682
  async () => storybookDevServer(fullOptions, server)
3152
3683
  ), mcp = getMcpMetadataFromMainConfig(config);
3153
3684
  await writeStorybookRuntimeInstanceRecord({
3154
- address: localAddress,
3685
+ address: `${new URL(localAddress).origin}${joinBasePath(options.basePath)}`,
3155
3686
  configDir: options.configDir,
3156
3687
  mcp,
3157
3688
  port,
@@ -3185,9 +3716,9 @@ async function buildDevStandalone(options) {
3185
3716
  updateInfo: versionCheck,
3186
3717
  version: storybookVersion,
3187
3718
  name,
3188
- address: localAddress,
3719
+ address: withInitialPath(localAddress, options.initialPath, options.basePath),
3189
3720
  host: options.host,
3190
- networkAddress,
3721
+ networkAddress: withInitialPath(networkAddress, options.initialPath, options.basePath),
3191
3722
  allowedHosts,
3192
3723
  managerTotalTime,
3193
3724
  previewTotalTime
@@ -3195,6 +3726,18 @@ async function buildDevStandalone(options) {
3195
3726
  }
3196
3727
  return { port, address: localAddress, networkAddress };
3197
3728
  }
3729
+ function watchParentProcess() {
3730
+ let parentPid = Number(process.env.FORKBOOK_PARENT_PID);
3731
+ if (!Number.isInteger(parentPid) || parentPid <= 0)
3732
+ return;
3733
+ globalThis.setInterval(() => {
3734
+ try {
3735
+ process.kill(parentPid, 0);
3736
+ } catch {
3737
+ process.exit(0);
3738
+ }
3739
+ }, 2e3).unref?.();
3740
+ }
3198
3741
 
3199
3742
  // src/core-server/build-index.ts
3200
3743
  import { writeFile as writeFile4 } from "node:fs/promises";
@@ -3212,15 +3755,14 @@ import {
3212
3755
  validateFrameworkName as validateFrameworkName2
3213
3756
  } from "@aussieljk/forkbook/internal/common";
3214
3757
  import { oneWayHash as oneWayHash2 } from "@aussieljk/forkbook/internal/telemetry";
3215
- import { global as global4 } from "@storybook/global";
3216
- import { dirname, isAbsolute, join as join9, relative as relative5, resolve as resolve7 } from "pathe";
3217
- async function loadStorybook(options) {
3218
- let configDir = resolve7(options.configDir), cacheKey = oneWayHash2(relative5(getProjectRoot2(), configDir));
3758
+ import { dirname as dirname3, isAbsolute as isAbsolute2, join as join11, relative as relative6, resolve as resolve8 } from "pathe";
3759
+ async function loadForkbook(options) {
3760
+ let configDir = resolve8(options.configDir), cacheKey = oneWayHash2(relative6(getProjectRoot2(), configDir));
3219
3761
  options.configType = "DEVELOPMENT", options.configDir = configDir, options.cacheKey = cacheKey;
3220
3762
  let channel = options.channel ?? new Channel4({});
3221
3763
  setChannel3(channel);
3222
3764
  let config = await loadMainConfig3(options), { framework } = config, corePresets = [], frameworkName = typeof framework == "string" ? framework : framework?.name;
3223
- validateFrameworkName2(frameworkName), frameworkName && corePresets.push(join9(frameworkName, "preset")), frameworkName = frameworkName || "custom";
3765
+ validateFrameworkName2(frameworkName), frameworkName && corePresets.push(join11(frameworkName, "preset")), frameworkName = frameworkName || "custom";
3224
3766
  let presets = await loadAllPresets3({
3225
3767
  corePresets,
3226
3768
  overridePresets: [
@@ -3231,12 +3773,12 @@ async function loadStorybook(options) {
3231
3773
  channel
3232
3774
  }), { renderer, builder } = await presets.apply("core", {}), resolvedRenderer = renderer && resolveAddonName3(options.configDir, renderer, options), builderName = typeof builder == "string" ? builder : builder?.name;
3233
3775
  if (builderName) {
3234
- let builderEntry = builderName.startsWith("file:") ? fileURLToPath(builderName) : builderName, builderPresetDir = isAbsolute(builderEntry) ? dirname(builderEntry) : resolvePackageDir(builderEntry), builderPreset = safeResolveModule({ specifier: join9(builderPresetDir, "preset.js") });
3776
+ let builderEntry = builderName.startsWith("file:") ? fileURLToPath(builderName) : builderName, builderPresetDir = isAbsolute2(builderEntry) ? dirname3(builderEntry) : resolvePackageDir(builderEntry), builderPreset = safeResolveModule({ specifier: join11(builderPresetDir, "preset.js") });
3235
3777
  builderPreset && corePresets.push(builderPreset);
3236
3778
  }
3237
3779
  presets = await loadAllPresets3({
3238
3780
  corePresets: [
3239
- join9(resolvePackageDir("@aussieljk/forkbook"), "dist/core-server/presets/common-preset.js"),
3781
+ join11(resolvePackageDir("@aussieljk/forkbook"), "dist/core-server/presets/common-preset.js"),
3240
3782
  ...resolvedRenderer ? [resolvedRenderer] : [],
3241
3783
  ...corePresets
3242
3784
  ],
@@ -3247,7 +3789,7 @@ async function loadStorybook(options) {
3247
3789
  channel
3248
3790
  });
3249
3791
  let features = await presets.apply("features");
3250
- return global4.FEATURES = features, await applyServicesPresetOnce(presets), {
3792
+ return global2.FEATURES = features, await applyServicesPresetOnce(presets), {
3251
3793
  ...options,
3252
3794
  // the resolved channel — the one the presets received — never the possibly-absent option
3253
3795
  channel,
@@ -3258,8 +3800,8 @@ async function loadStorybook(options) {
3258
3800
 
3259
3801
  // src/core-server/utils/StoryIndexGenerator.ts
3260
3802
  import { existsSync as existsSync3 } from "node:fs";
3261
- import { readFile as readFile4 } from "node:fs/promises";
3262
- import { dirname as dirname2, extname, join as join10, normalize as normalize2, relative as relative6, resolve as resolve8, sep as sep2 } from "node:path";
3803
+ import { readFile as readFile6 } from "node:fs/promises";
3804
+ import { dirname as dirname4, extname, join as join12, normalize as normalize3, relative as relative7, resolve as resolve9, sep as sep2 } from "node:path";
3263
3805
  import {
3264
3806
  commonGlobOptions as commonGlobOptions2,
3265
3807
  getProjectRoot as getProjectRoot3,
@@ -3267,19 +3809,63 @@ import {
3267
3809
  normalizeStoryPath
3268
3810
  } from "@aussieljk/forkbook/internal/common";
3269
3811
  import { combineTags, storyNameFromExport, toId } from "@aussieljk/forkbook/internal/csf/csf-utils";
3270
- import { loadConfig } from "@aussieljk/forkbook/internal/csf-tools";
3271
- import { logger as logger16, once } from "@aussieljk/forkbook/internal/node-logger";
3812
+ import { loadConfig as loadConfig2 } from "@aussieljk/forkbook/internal/csf-tools";
3813
+ import { logger as logger16, once as once2 } from "@aussieljk/forkbook/internal/node-logger";
3272
3814
  import { isExampleStoryId as isExampleStoryId2 } from "@aussieljk/forkbook/internal/telemetry";
3273
3815
  var import_picocolors7 = __toESM(require_picocolors(), 1);
3274
3816
  var TsconfigPaths = __toESM(require_lib(), 1);
3275
- import { dedent as dedent7 } from "ts-dedent";
3817
+ import { dedent as dedent8 } from "ts-dedent";
3276
3818
 
3277
3819
  // src/docs-tools/shared.ts
3278
3820
  var ADDON_ID = "@aussieljk/forkbook/docs", PANEL_ID = `${ADDON_ID}/panel`;
3279
3821
  var anchorBlockIdFromId = (storyId) => `anchor--${storyId}`, SNIPPET_RENDERED = `${ADDON_ID}/snippet-rendered`;
3280
3822
 
3281
- // src/shared/story-index/sortStories.ts
3823
+ // src/core-server/utils/get-story-sort-parameter.ts
3824
+ import { generate } from "@aussieljk/forkbook/internal/babel";
3825
+ import { loadConfig } from "@aussieljk/forkbook/internal/csf-tools";
3826
+ import { once } from "@aussieljk/forkbook/internal/node-logger";
3827
+ import { transformSync } from "rolldown/utils";
3282
3828
  import { dedent as dedent6 } from "ts-dedent";
3829
+ var STORY_SORT_PATH = ["parameters", "options", "storySort"];
3830
+ function getStorySortParameter(previewCode) {
3831
+ if (!previewCode || !previewCode.includes("storySort"))
3832
+ return;
3833
+ let node, config;
3834
+ try {
3835
+ config = loadConfig(previewCode).parse(), node = config.get(STORY_SORT_PATH);
3836
+ } catch {
3837
+ return;
3838
+ }
3839
+ if (!node)
3840
+ return;
3841
+ let nodeType = node.type;
3842
+ if (nodeType === "ArrowFunctionExpression" || nodeType === "FunctionExpression" || nodeType === "ObjectMethod")
3843
+ try {
3844
+ let source = generate(node).code, wrapped = `export default (${nodeType === "ObjectMethod" ? `function ${source}` : source});`, { code, errors } = transformSync("story-sort.tsx", wrapped, { lang: "tsx" });
3845
+ if (errors.length)
3846
+ throw new Error(errors[0].message);
3847
+ let body = code.replace(/export default\s*/, "return ");
3848
+ return new Function(body)();
3849
+ } catch (err) {
3850
+ once.warn(dedent6`
3851
+ Unable to evaluate parameters.options.storySort from the preview file. The function must
3852
+ not use imports or variables from outside its body.
3853
+
3854
+ ${String(err)}
3855
+ `);
3856
+ return;
3857
+ }
3858
+ let value = config.getValue(STORY_SORT_PATH);
3859
+ if (value && typeof value == "object")
3860
+ return value;
3861
+ once.warn(dedent6`
3862
+ Unable to read parameters.options.storySort from the preview file. Use an inline object, for
3863
+ example { order: ['Intro', 'Components'] }, or an inline function.
3864
+ `);
3865
+ }
3866
+
3867
+ // src/shared/story-index/sortStories.ts
3868
+ import { dedent as dedent7 } from "ts-dedent";
3283
3869
 
3284
3870
  // src/shared/story-index/storySort.ts
3285
3871
  var STORY_KIND_PATH_SEPARATOR = /\s*\/\s*/, storySort = (options = {}) => (a, b) => {
@@ -3330,14 +3916,14 @@ var toComparator = (storySortParameter) => typeof storySortParameter == "functio
3330
3916
  try {
3331
3917
  return sortStoriesCommon(stories, storySortParameter, fileNameOrder);
3332
3918
  } catch (err) {
3333
- throw new Error(dedent6`
3919
+ throw new Error(dedent7`
3334
3920
  Error sorting stories with sort parameter ${storySortParameter}:
3335
3921
 
3336
3922
  > ${err.message}
3337
3923
 
3338
3924
  Are you using a V6-style sort function in V7 mode?
3339
3925
 
3340
- More info: https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#v7-style-story-sort
3926
+ More info: https://forkbook.ljk.dev/docs/migration#v7-style-story-sort
3341
3927
  `);
3342
3928
  }
3343
3929
  };
@@ -3519,7 +4105,7 @@ var addStats = (stat2, acc) => {
3519
4105
  };
3520
4106
 
3521
4107
  // src/core-server/utils/StoryIndexGenerator.ts
3522
- var makeAbsolute = (otherImport, normalizedPath, workingDir) => otherImport.startsWith(".") ? slash(resolve8(workingDir, normalizeStoryPath(join10(dirname2(normalizedPath), otherImport)))) : otherImport, StoryIndexGenerator = class _StoryIndexGenerator {
4108
+ var makeAbsolute = (otherImport, normalizedPath, workingDir) => otherImport.startsWith(".") ? slash(resolve9(workingDir, normalizeStoryPath(join12(dirname4(normalizedPath), otherImport)))) : otherImport, StoryIndexGenerator = class _StoryIndexGenerator {
3523
4109
  constructor(specifiers, options) {
3524
4110
  this.specifiers = specifiers;
3525
4111
  this.options = options;
@@ -3547,20 +4133,21 @@ var makeAbsolute = (otherImport, normalizedPath, workingDir) => otherImport.star
3547
4133
  let cacheKey = this.getFindMatchingFilesCacheKey(specifier, workingDir, ignoreWarnings), cached = this.findMatchingFilesCache.get(cacheKey);
3548
4134
  if (cached)
3549
4135
  return cached;
3550
- let pathToSubIndex = {}, globCwd = slash(resolve8(workingDir, specifier.directory)), globPattern = specifier.files.startsWith("!") ? `./${specifier.files}` : specifier.files, { globby } = await import("../_node-chunks/globby-OEMHPBFY.js"), files = await globby(globPattern, {
4136
+ let pathToSubIndex = {}, globCwd = slash(resolve9(workingDir, specifier.directory)), globPattern = specifier.files.startsWith("!") ? `./${specifier.files}` : specifier.files, { glob: glob2 } = await import("../_node-chunks/dist-XPLJ5T4W.js"), files = await glob2(globPattern, {
3551
4137
  absolute: !0,
4138
+ expandDirectories: !1,
3552
4139
  cwd: globCwd,
3553
4140
  ...commonGlobOptions2(globPattern),
3554
4141
  onlyFiles: !0
3555
4142
  });
3556
- return files.length === 0 && !ignoreWarnings && once.warn(
4143
+ return files.length === 0 && !ignoreWarnings && once2.warn(
3557
4144
  `No story files found for the specified pattern: ${import_picocolors7.default.blue(
3558
- join10(specifier.directory, specifier.files)
4145
+ join12(specifier.directory, specifier.files)
3559
4146
  )}`
3560
4147
  ), files.sort().forEach((absolutePath) => {
3561
4148
  let ext = extname(absolutePath);
3562
4149
  if (ext === ".storyshot") {
3563
- let relativePath = relative6(workingDir, absolutePath);
4150
+ let relativePath = relative7(workingDir, absolutePath);
3564
4151
  logger16.info(`Skipping ${ext} file ${relativePath}`);
3565
4152
  return;
3566
4153
  }
@@ -3584,7 +4171,7 @@ var makeAbsolute = (otherImport, normalizedPath, workingDir) => otherImport.star
3584
4171
  this.specifiers,
3585
4172
  this.options.workingDir
3586
4173
  )).forEach(
3587
- ([specifier, cache4]) => this.specifierToCache.set(specifier, cache4)
4174
+ ([specifier, cache5]) => this.specifierToCache.set(specifier, cache5)
3588
4175
  );
3589
4176
  let previewCode = await this.getPreviewCode(), projectTags = this.getProjectTags(previewCode);
3590
4177
  await this.ensureExtracted({ projectTags });
@@ -3605,7 +4192,7 @@ var makeAbsolute = (otherImport, normalizedPath, workingDir) => otherImport.star
3605
4192
  try {
3606
4193
  entry[absolutePath] = await updater(specifier, absolutePath, entry[absolutePath]);
3607
4194
  } catch (err) {
3608
- let relativePath = `.${sep2}${relative6(this.options.workingDir, absolutePath)}`;
4195
+ let relativePath = `.${sep2}${relative7(this.options.workingDir, absolutePath)}`;
3609
4196
  entry[absolutePath] = {
3610
4197
  type: "error",
3611
4198
  err: new IndexingError(
@@ -3633,13 +4220,13 @@ var makeAbsolute = (otherImport, normalizedPath, workingDir) => otherImport.star
3633
4220
  );
3634
4221
  let statsSummary = {};
3635
4222
  return { entries: this.specifiers.flatMap((specifier) => {
3636
- let cache4 = this.specifierToCache.get(specifier);
4223
+ let cache5 = this.specifierToCache.get(specifier);
3637
4224
  return invariant(
3638
- cache4,
4225
+ cache5,
3639
4226
  `specifier does not have a matching cache entry in specifierToCache: ${JSON.stringify(
3640
4227
  specifier
3641
4228
  )}`
3642
- ), Object.values(cache4).flatMap((entry) => entry ? entry.type === "docs" ? [entry] : entry.type === "error" ? [entry] : entry.entries.map((item) => {
4229
+ ), Object.values(cache5).flatMap((entry) => entry ? entry.type === "docs" ? [entry] : entry.type === "error" ? [entry] : entry.entries.map((item) => {
3643
4230
  if (item.type === "docs")
3644
4231
  return item;
3645
4232
  isExampleStoryId2(item.id) || addStats(item.extra.stats, statsSummary);
@@ -3650,7 +4237,7 @@ var makeAbsolute = (otherImport, normalizedPath, workingDir) => otherImport.star
3650
4237
  }
3651
4238
  findDependencies(absoluteImports) {
3652
4239
  return [...this.specifierToCache.values()].flatMap(
3653
- (cache4) => Object.entries(cache4).filter(([fileName, cacheEntry]) => !cacheEntry || cacheEntry.type !== "stories" ? !1 : !!absoluteImports.find(
4240
+ (cache5) => Object.entries(cache5).filter(([fileName, cacheEntry]) => !cacheEntry || cacheEntry.type !== "stories" ? !1 : !!absoluteImports.find(
3654
4241
  (storyImport) => fileName.match(
3655
4242
  new RegExp(`^${storyImport.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(\\.[^.]+)?$`)
3656
4243
  )
@@ -3666,15 +4253,15 @@ var makeAbsolute = (otherImport, normalizedPath, workingDir) => otherImport.star
3666
4253
  resolveComponentPath(rawComponentPath, absolutePath, matchPath) {
3667
4254
  let matchedPath = matchPath?.(rawComponentPath, void 0, void 0, supportedExtensions) ?? rawComponentPath, resolved;
3668
4255
  try {
3669
- resolved = resolveImport(matchedPath, { basedir: dirname2(absolutePath) });
4256
+ resolved = resolveImport(matchedPath, { basedir: dirname4(absolutePath) });
3670
4257
  } catch {
3671
4258
  return matchedPath;
3672
4259
  }
3673
- let relativePath = relative6(this.options.workingDir, resolved);
4260
+ let relativePath = relative7(this.options.workingDir, resolved);
3674
4261
  return slash(normalizeStoryPath(relativePath));
3675
4262
  }
3676
4263
  async extractStories(specifier, absolutePath, projectTags = []) {
3677
- let relativePath = relative6(this.options.workingDir, absolutePath), importPath = slash(normalizeStoryPath(relativePath)), defaultMakeTitle = (userTitle) => {
4264
+ let relativePath = relative7(this.options.workingDir, absolutePath), importPath = slash(normalizeStoryPath(relativePath)), defaultMakeTitle = (userTitle) => {
3678
4265
  let title = userOrAutoTitleFromSpecifier(importPath, specifier, userTitle);
3679
4266
  return invariant(
3680
4267
  title,
@@ -3693,7 +4280,7 @@ var makeAbsolute = (otherImport, normalizedPath, workingDir) => otherImport.star
3693
4280
  tsconfig.paths,
3694
4281
  ["browser", "module", "main"]
3695
4282
  ));
3696
- let toImportPath = (path) => path ? path.startsWith("virtual:") ? path : slash(normalizeStoryPath(relative6(this.options.workingDir, path))) : importPath, storyEntries = indexInputs.map((input) => {
4283
+ let toImportPath = (path) => path ? path.startsWith("virtual:") ? path : slash(normalizeStoryPath(relative7(this.options.workingDir, path))) : importPath, storyEntries = indexInputs.map((input) => {
3697
4284
  let name = input.name ?? storyNameFromExport(input.exportName), componentPath = input.rawComponentPath && this.resolveComponentPath(input.rawComponentPath, absolutePath, matchPath), title = input.title ?? defaultMakeTitle(), id = input.__id ?? toId(input.metaId ?? title, storyNameFromExport(input.exportName)), tags = combineTags(...projectTags, ...input.tags ?? []), subtype = input.subtype ?? "story", entry = {
3698
4285
  type: "story",
3699
4286
  subtype,
@@ -3708,7 +4295,9 @@ var makeAbsolute = (otherImport, normalizedPath, workingDir) => otherImport.star
3708
4295
  componentPath,
3709
4296
  tags
3710
4297
  };
3711
- return subtype === "test" && (entry.parent = input.parent, entry.parentName = input.parentName), input.exportName && (entry.exportName = input.exportName), entry;
4298
+ subtype === "test" && (entry.parent = input.parent, entry.parentName = input.parentName), input.exportName && (entry.exportName = input.exportName);
4299
+ let thumbnail = resolveThumbnail(input.thumbnail, absolutePath, this.options.workingDir);
4300
+ return thumbnail && (entry.thumbnail = thumbnail), entry;
3712
4301
  });
3713
4302
  if (storyEntries.some((entry) => entry.tags.includes(Tag.AUTODOCS)) && !!this.options.docs && this.options.build?.test?.disableAutoDocs !== !0) {
3714
4303
  let name = this.options.docs?.defaultName ?? "Docs", { metaId } = indexInputs[0], entry = storyEntries[0], id = toId(metaId ?? entry.title, name), tags = combineTags(...projectTags, ...indexInputs[0].tags ?? []);
@@ -3738,9 +4327,9 @@ var makeAbsolute = (otherImport, normalizedPath, workingDir) => otherImport.star
3738
4327
  };
3739
4328
  }
3740
4329
  async extractDocs(specifier, absolutePath, projectTags = []) {
3741
- let relativePath = relative6(this.options.workingDir, absolutePath);
4330
+ let relativePath = relative7(this.options.workingDir, absolutePath);
3742
4331
  try {
3743
- let normalizedPath = normalizeStoryPath(relativePath), importPath = slash(normalizedPath), content = await readFile4(absolutePath, { encoding: "utf8" }), result = await analyzeMdx(content);
4332
+ let normalizedPath = normalizeStoryPath(relativePath), importPath = slash(normalizedPath), content = await readFile6(absolutePath, { encoding: "utf8" }), result = await analyzeMdx(content);
3744
4333
  if (result.isTemplate)
3745
4334
  return !1;
3746
4335
  let absoluteImports = result.imports.map(
@@ -3751,8 +4340,8 @@ var makeAbsolute = (otherImport, normalizedPath, workingDir) => otherImport.star
3751
4340
  dependencies.forEach((dep) => {
3752
4341
  if (dep.entries.length > 0) {
3753
4342
  let first = dep.entries.find((e) => e.type !== "docs");
3754
- normalize2(resolve8(this.options.workingDir, first.importPath)).startsWith(
3755
- normalize2(absoluteOf)
4343
+ normalize3(resolve9(this.options.workingDir, first.importPath)).startsWith(
4344
+ normalize3(absoluteOf)
3756
4345
  ) && (csfEntry = first, metaDependency = dep);
3757
4346
  }
3758
4347
  }), metaDependency && (sortedDependencies = [
@@ -3760,7 +4349,7 @@ var makeAbsolute = (otherImport, normalizedPath, workingDir) => otherImport.star
3760
4349
  ...dependencies.filter((d) => d !== metaDependency)
3761
4350
  ]), invariant(
3762
4351
  csfEntry,
3763
- dedent7`
4352
+ dedent8`
3764
4353
  Could not find or load CSF file at path "${result.of}" referenced by \`of={}\` in docs file "${relativePath}".
3765
4354
 
3766
4355
  - Does that file exist?
@@ -3797,7 +4386,7 @@ var makeAbsolute = (otherImport, normalizedPath, workingDir) => otherImport.star
3797
4386
  } catch (err) {
3798
4387
  throw err && err.source?.match(/mdast-util-mdx-jsx/g) && logger16.warn(
3799
4388
  `\u{1F4A1} This seems to be an MDX2 syntax error. Please refer to the MDX section in the following resource for assistance on how to fix this: ${import_picocolors7.default.yellow(
3800
- "https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#mdx2-upgrade"
4389
+ "https://forkbook.ljk.dev/docs/migration#mdx2-upgrade"
3801
4390
  )}`
3802
4391
  ), err;
3803
4392
  }
@@ -3854,6 +4443,45 @@ var makeAbsolute = (otherImport, normalizedPath, workingDir) => otherImport.star
3854
4443
  async getIndex() {
3855
4444
  return (await this.getIndexAndStats()).storyIndex;
3856
4445
  }
4446
+ /**
4447
+ * Like `getIndex`, but when some story files fail to index, return the entries of the other files
4448
+ * and list the bad files in `errors`. Errors that affect the whole index (for example duplicate
4449
+ * story ids) still throw.
4450
+ */
4451
+ async getIndexWithFileErrors() {
4452
+ try {
4453
+ return await this.getIndex();
4454
+ } catch (err) {
4455
+ if (this.lastPartialIndex)
4456
+ return this.lastPartialIndex;
4457
+ throw err;
4458
+ }
4459
+ }
4460
+ async buildPartialIndex(storiesList, projectTags, fileErrors) {
4461
+ let indexEntries = {};
4462
+ try {
4463
+ for (let entry of storiesList) {
4464
+ if (entry.type === "error")
4465
+ continue;
4466
+ let existing = indexEntries[entry.id];
4467
+ indexEntries[entry.id] = existing ? this.chooseDuplicate(existing, entry, projectTags ?? []) : entry;
4468
+ }
4469
+ return {
4470
+ v: 5,
4471
+ entries: await this.sortStories(
4472
+ indexEntries,
4473
+ combineStorySorts(this.options.storySorts ?? [])
4474
+ ),
4475
+ errors: fileErrors.map((err) => ({
4476
+ importPath: slash(err.importPaths[0] ?? ""),
4477
+ importPaths: err.importPaths.map((path) => slash(path)),
4478
+ message: err.message
4479
+ }))
4480
+ };
4481
+ } catch {
4482
+ return null;
4483
+ }
4484
+ }
3857
4485
  async getIndexAndStats() {
3858
4486
  if (this.lastIndex && this.lastStats)
3859
4487
  return { storyIndex: this.lastIndex, stats: this.lastStats };
@@ -3862,8 +4490,10 @@ var makeAbsolute = (otherImport, normalizedPath, workingDir) => otherImport.star
3862
4490
  let previewCode = await this.getPreviewCode(), projectTags = this.getProjectTags(previewCode), { entries: storiesList, stats } = await this.ensureExtracted({ projectTags });
3863
4491
  try {
3864
4492
  let errorEntries = storiesList.filter((entry) => entry.type === "error");
3865
- if (errorEntries.length)
3866
- throw new MultipleIndexingError(errorEntries.map((entry) => entry.err));
4493
+ if (errorEntries.length) {
4494
+ let fileErrors = errorEntries.map((entry) => entry.err);
4495
+ throw this.lastPartialIndex = await this.buildPartialIndex(storiesList, projectTags, fileErrors), new MultipleIndexingError(fileErrors);
4496
+ }
3867
4497
  let duplicateErrors = [], indexEntries = {};
3868
4498
  if (storiesList.forEach((entry) => {
3869
4499
  try {
@@ -3874,9 +4504,12 @@ var makeAbsolute = (otherImport, normalizedPath, workingDir) => otherImport.star
3874
4504
  }
3875
4505
  }), duplicateErrors.length)
3876
4506
  throw new MultipleIndexingError(duplicateErrors);
3877
- let sorted = await this.sortStories(
4507
+ let previewStorySort = getStorySortParameter(previewCode), sorted = await this.sortStories(
3878
4508
  indexEntries,
3879
- combineStorySorts(this.options.storySorts ?? [])
4509
+ combineStorySorts([
4510
+ ...this.options.storySorts ?? [],
4511
+ ...previewStorySort ? [previewStorySort] : []
4512
+ ])
3880
4513
  );
3881
4514
  return this.lastStats = stats, this.lastIndex = {
3882
4515
  v: 5,
@@ -3887,26 +4520,26 @@ var makeAbsolute = (otherImport, normalizedPath, workingDir) => otherImport.star
3887
4520
  }
3888
4521
  }
3889
4522
  invalidateAll() {
3890
- this.specifierToCache.forEach((cache4) => {
3891
- Object.keys(cache4).forEach((key) => {
3892
- cache4[key] = !1;
4523
+ this.specifierToCache.forEach((cache5) => {
4524
+ Object.keys(cache5).forEach((key) => {
4525
+ cache5[key] = !1;
3893
4526
  });
3894
- }), this.lastIndex = null, this.lastError = null, this.invalidationListeners.forEach((listener) => listener());
4527
+ }), this.lastIndex = null, this.lastError = null, this.lastPartialIndex = null, this.invalidationListeners.forEach((listener) => listener());
3895
4528
  }
3896
4529
  invalidate(importPath, removed) {
3897
- let absolutePath = slash(resolve8(this.options.workingDir, importPath)), specifier = Array.from(this.specifierToCache.keys()).find(
4530
+ let added = !1, wasRemoved = !1, absolutePath = slash(resolve9(this.options.workingDir, importPath)), specifier = Array.from(this.specifierToCache.keys()).find(
3898
4531
  (ns) => ns.importPathMatcher.exec(importPath)
3899
4532
  );
3900
4533
  if (!specifier)
3901
4534
  return;
3902
- let cache4 = this.specifierToCache.get(specifier);
4535
+ let cache5 = this.specifierToCache.get(specifier);
3903
4536
  invariant(
3904
- cache4,
4537
+ cache5,
3905
4538
  `specifier does not have a matching cache entry in specifierToCache: ${JSON.stringify(
3906
4539
  specifier
3907
4540
  )}`
3908
4541
  );
3909
- let cacheEntry = cache4[absolutePath];
4542
+ let cacheEntry = cache5[absolutePath];
3910
4543
  if (cacheEntry && cacheEntry.type === "stories") {
3911
4544
  let { dependents } = cacheEntry, invalidated = /* @__PURE__ */ new Set();
3912
4545
  this.specifierToCache.forEach((otherCache) => {
@@ -3918,16 +4551,18 @@ var makeAbsolute = (otherImport, normalizedPath, workingDir) => otherImport.star
3918
4551
  if (removed) {
3919
4552
  if (cacheEntry && cacheEntry.type === "docs") {
3920
4553
  let absoluteImports = cacheEntry.storiesImports.map(
3921
- (p) => resolve8(this.options.workingDir, p)
4554
+ (p) => resolve9(this.options.workingDir, p)
3922
4555
  );
3923
4556
  this.findDependencies(absoluteImports).forEach(
3924
4557
  (dep) => dep.dependents.splice(dep.dependents.indexOf(absolutePath), 1)
3925
4558
  );
3926
4559
  }
3927
- delete cache4[absolutePath];
4560
+ wasRemoved = absolutePath in cache5, delete cache5[absolutePath];
3928
4561
  } else
3929
- cache4[absolutePath] = !1;
3930
- this.lastIndex = null, this.lastError = null, this.invalidationListeners.forEach((listener) => listener());
4562
+ added = !(absolutePath in cache5), cache5[absolutePath] = !1;
4563
+ this.lastIndex = null, this.lastError = null, this.lastPartialIndex = null;
4564
+ let event = { importPath, added, removed: wasRemoved };
4565
+ this.invalidationListeners.forEach((listener) => listener(event));
3931
4566
  }
3932
4567
  onInvalidated(listener) {
3933
4568
  return this.invalidationListeners.add(listener), () => {
@@ -3935,14 +4570,14 @@ var makeAbsolute = (otherImport, normalizedPath, workingDir) => otherImport.star
3935
4570
  };
3936
4571
  }
3937
4572
  async getPreviewCode() {
3938
- let previewFile = ["js", "jsx", "ts", "tsx", "mjs", "cjs", "mts"].map((ext) => join10(this.options.configDir, `preview.${ext}`)).find((fname) => existsSync3(fname));
3939
- return previewFile && (await readFile4(previewFile, { encoding: "utf8" })).toString();
4573
+ let previewFile = ["js", "jsx", "ts", "tsx", "mjs", "cjs", "mts"].map((ext) => join12(this.options.configDir, `preview.${ext}`)).find((fname) => existsSync3(fname));
4574
+ return previewFile && (await readFile6(previewFile, { encoding: "utf8" })).toString();
3940
4575
  }
3941
4576
  getProjectTags(previewCode) {
3942
4577
  let projectTags = [], defaultTags = [Tag.DEV, Tag.TEST, Tag.MANIFEST];
3943
4578
  if (previewCode)
3944
4579
  try {
3945
- let projectAnnotations = loadConfig(previewCode).parse(), tags = projectAnnotations.getValue(["tags"]) ?? [];
4580
+ let projectAnnotations = loadConfig2(previewCode).parse(), tags = projectAnnotations.getValue(["tags"]) ?? [];
3946
4581
  invariant(
3947
4582
  !projectAnnotations.mutationDiagnostics.some(
3948
4583
  ({ code }) => code === "unsupported-value"
@@ -3950,7 +4585,7 @@ var makeAbsolute = (otherImport, normalizedPath, workingDir) => otherImport.star
3950
4585
  "Preview tags must be a static array of strings"
3951
4586
  ), projectTags = tags;
3952
4587
  } catch {
3953
- once.warn(dedent7`
4588
+ once2.warn(dedent8`
3954
4589
  Unable to parse tags from project configuration. If defined, tags should be specified inline, e.g.
3955
4590
 
3956
4591
  export default {
@@ -3974,7 +4609,7 @@ var makeAbsolute = (otherImport, normalizedPath, workingDir) => otherImport.star
3974
4609
 
3975
4610
  // src/core-server/build-index.ts
3976
4611
  var buildIndex = async (options) => {
3977
- let { presets } = await loadStorybook(options), [indexers, stories, docsOptions, features] = await Promise.all([
4612
+ let { presets } = await loadForkbook(options), [indexers, stories, docsOptions, features] = await Promise.all([
3978
4613
  presets.apply("experimental_indexers", []),
3979
4614
  presets.apply("stories", []),
3980
4615
  presets.apply("docs"),
@@ -4032,7 +4667,7 @@ var getStoriesPathsFromConfig = async ({
4032
4667
  workingDir,
4033
4668
  !0
4034
4669
  )).flatMap(
4035
- ([specifier, cache4]) => StoryIndexGenerator.storyFileNames(/* @__PURE__ */ new Map([[specifier, cache4]]))
4670
+ ([specifier, cache5]) => StoryIndexGenerator.storyFileNames(/* @__PURE__ */ new Map([[specifier, cache5]]))
4036
4671
  );
4037
4672
  };
4038
4673
 
@@ -4065,7 +4700,7 @@ function createWorkerGatedStoryDocsProvider({
4065
4700
 
4066
4701
  // src/shared/universal-store/mock.ts
4067
4702
  import { Channel as Channel5 } from "@aussieljk/forkbook/internal/channels";
4068
- import { dedent as dedent8 } from "ts-dedent";
4703
+ import { dedent as dedent9 } from "ts-dedent";
4069
4704
  var MockUniversalStore = class _MockUniversalStore extends UniversalStore {
4070
4705
  constructor(options, testUtils) {
4071
4706
  UniversalStore.isInternalConstructing = !0, super(
@@ -4074,13 +4709,14 @@ var MockUniversalStore = class _MockUniversalStore extends UniversalStore {
4074
4709
  ), UniversalStore.isInternalConstructing = !1, typeof testUtils?.fn == "function" && (this.testUtils = testUtils, this.getState = testUtils.fn(this.getState), this.setState = testUtils.fn(this.setState), this.subscribe = testUtils.fn(this.subscribe), this.onStateChange = testUtils.fn(this.onStateChange), this.send = testUtils.fn(this.send));
4075
4710
  }
4076
4711
  /** Create a mock universal store. This is just an alias for the constructor */
4712
+ // `State = any`: as in `UniversalStore.create`, a store made without a state type takes any state.
4077
4713
  static create(options, testUtils) {
4078
4714
  return new _MockUniversalStore(options, testUtils);
4079
4715
  }
4080
4716
  unsubscribeAll() {
4081
4717
  if (!this.testUtils)
4082
4718
  throw new Error(
4083
- dedent8`Cannot call unsubscribeAll on a store that does not have testUtils.
4719
+ dedent9`Cannot call unsubscribeAll on a store that does not have testUtils.
4084
4720
  Please provide testUtils as the second argument when creating the store.`
4085
4721
  );
4086
4722
  let callReturnedUnsubscribeFn = (result) => {
@@ -4092,11 +4728,638 @@ var MockUniversalStore = class _MockUniversalStore extends UniversalStore {
4092
4728
  this.subscribe.mock?.results.forEach(callReturnedUnsubscribeFn), this.onStateChange.mock?.results.forEach(callReturnedUnsubscribeFn);
4093
4729
  }
4094
4730
  };
4731
+
4732
+ // src/core-server/utils/request-guards.ts
4733
+ var SAME_SITE_FETCH_VALUES = /* @__PURE__ */ new Set(["same-origin", "none"]), firstHeader = (value) => Array.isArray(value) ? value[0] : value;
4734
+ function isCrossSiteRequest(req, hostValidation) {
4735
+ let fetchSite = firstHeader(req.headers["sec-fetch-site"])?.trim().toLowerCase();
4736
+ if (fetchSite && !SAME_SITE_FETCH_VALUES.has(fetchSite)) {
4737
+ let method = req.method?.toUpperCase();
4738
+ if (!((method === "GET" || method === "HEAD") && firstHeader(req.headers["sec-fetch-mode"])?.trim().toLowerCase() === "navigate"))
4739
+ return !0;
4740
+ }
4741
+ let origin = firstHeader(req.headers.origin);
4742
+ if (!origin)
4743
+ return !1;
4744
+ try {
4745
+ return !isValidHost(new URL(origin).host, hostValidation);
4746
+ } catch {
4747
+ return !0;
4748
+ }
4749
+ }
4750
+ var RequestBodyTooLargeError = class extends Error {
4751
+ constructor(limit) {
4752
+ super(`Request body is larger than ${limit} bytes`);
4753
+ this.limit = limit;
4754
+ this.name = "RequestBodyTooLargeError";
4755
+ }
4756
+ };
4757
+ async function readRequestBody(req, maxBytes) {
4758
+ let declared = Number(firstHeader(req.headers["content-length"]));
4759
+ if (Number.isFinite(declared) && declared > maxBytes)
4760
+ throw new RequestBodyTooLargeError(maxBytes);
4761
+ let chunks = [], size = 0;
4762
+ for await (let chunk of req) {
4763
+ let data = Buffer.from(chunk);
4764
+ if (size += data.length, size > maxBytes)
4765
+ throw new RequestBodyTooLargeError(maxBytes);
4766
+ chunks.push(data);
4767
+ }
4768
+ return Buffer.concat(chunks);
4769
+ }
4770
+ function sendPayloadTooLarge(res, error, contentType = "text/plain") {
4771
+ res.writeHead(413, { "Content-Type": contentType, Connection: "close" }), res.end(
4772
+ contentType === "application/json" ? JSON.stringify({ error: error.message }) : error.message
4773
+ );
4774
+ }
4775
+
4776
+ // src/core-server/utils/ghost-stories/get-candidates.ts
4777
+ import { readFile as readFile7 } from "node:fs/promises";
4778
+ import { babelParse, traverse } from "@aussieljk/forkbook/internal/babel";
4779
+
4780
+ // src/core-server/utils/ghost-stories/component-analyzer.ts
4781
+ var COMPLEXITY_CONFIG = {
4782
+ /** Weight applied to non-empty lines */
4783
+ locWeight: 1,
4784
+ /** Imports can be cheap, so they get a lower weight */
4785
+ importWeight: 0.5,
4786
+ /**
4787
+ * Defines what raw complexity value should map to the upper bound of a "simple" file For instance
4788
+ * 30 LOC + 4 imports = 32. This would result in a score of 0.3
4789
+ */
4790
+ simpleBaseline: 32,
4791
+ simpleScore: 0.3
4792
+ }, getComponentComplexity = (fileContent) => {
4793
+ let lines = fileContent.split(`
4794
+ `), nonEmptyLines = lines.filter((line) => line.trim() !== "").length, importCount = lines.filter((line) => line.trim().startsWith("import")).length, normalizedScore = (nonEmptyLines * COMPLEXITY_CONFIG.locWeight + importCount * COMPLEXITY_CONFIG.importWeight) / (COMPLEXITY_CONFIG.simpleBaseline / COMPLEXITY_CONFIG.simpleScore);
4795
+ return Math.min(normalizedScore, 1);
4796
+ };
4797
+
4798
+ // src/core-server/utils/ghost-stories/get-candidates.ts
4799
+ function isValidCandidate(source) {
4800
+ let ast = babelParse(source), hasJSX = !1, hasExport = !1;
4801
+ return traverse(ast, {
4802
+ JSXElement(path) {
4803
+ hasJSX = !0, hasExport && path.stop();
4804
+ },
4805
+ JSXFragment(path) {
4806
+ hasJSX = !0, hasExport && path.stop();
4807
+ },
4808
+ ExportNamedDeclaration(path) {
4809
+ hasExport = !0, hasJSX && path.stop();
4810
+ },
4811
+ ExportDefaultDeclaration(path) {
4812
+ hasExport = !0, hasJSX && path.stop();
4813
+ },
4814
+ ExportAllDeclaration(path) {
4815
+ hasExport = !0, hasJSX && path.stop();
4816
+ }
4817
+ }), hasJSX && hasExport;
4818
+ }
4819
+ async function getCandidatesForStorybook(files, sampleCount) {
4820
+ let simpleCandidates = [], analyzedCandidates = [];
4821
+ for (let file of files) {
4822
+ let source;
4823
+ try {
4824
+ if (source = await readFile7(file, "utf-8"), !isValidCandidate(source))
4825
+ continue;
4826
+ } catch {
4827
+ continue;
4828
+ }
4829
+ let complexity = getComponentComplexity(source);
4830
+ if (analyzedCandidates.push({ file, complexity }), complexity < 0.3 && (simpleCandidates.push({ file, complexity }), simpleCandidates.length >= sampleCount))
4831
+ break;
4832
+ }
4833
+ let selectedCandidates = [];
4834
+ simpleCandidates.length >= sampleCount ? selectedCandidates = simpleCandidates.sort((a, b) => a.complexity - b.complexity).slice(0, sampleCount) : selectedCandidates = analyzedCandidates.sort((a, b) => a.complexity - b.complexity).slice(0, sampleCount);
4835
+ let avgComplexity = selectedCandidates.length > 0 ? Number(
4836
+ (selectedCandidates.reduce((acc, curr) => acc + curr.complexity, 0) / selectedCandidates.length).toFixed(2)
4837
+ ) : 0;
4838
+ return {
4839
+ candidates: selectedCandidates.map(({ file }) => file),
4840
+ analyzedCount: analyzedCandidates.length,
4841
+ avgComplexity
4842
+ };
4843
+ }
4844
+ async function getComponentCandidates({
4845
+ sampleSize = 20,
4846
+ globPattern = "**/*.{tsx,jsx}",
4847
+ cwd = process.cwd()
4848
+ } = {}) {
4849
+ let globMatchCount = 0;
4850
+ try {
4851
+ let files = [];
4852
+ if (files = await glob(globPattern, {
4853
+ cwd,
4854
+ absolute: !0,
4855
+ expandDirectories: !1,
4856
+ ignore: [
4857
+ "**/node_modules/**",
4858
+ "**/.git/**",
4859
+ "**/dist/**",
4860
+ "**/__mocks__/**",
4861
+ "**/build/**",
4862
+ "**/forkbook-static/**",
4863
+ "**/*.test.*",
4864
+ "**/*.d.*",
4865
+ "**/*.config.*",
4866
+ "**/*.spec.*",
4867
+ "**/*.stories.*",
4868
+ // skip example story files that come from the CLI
4869
+ "**/stories/{Button,Header,Page}.*",
4870
+ "**/stories/{button,header,page}.*"
4871
+ ]
4872
+ }), globMatchCount = files.length, globMatchCount === 0)
4873
+ return {
4874
+ candidates: [],
4875
+ globMatchCount
4876
+ };
4877
+ let { analyzedCount, avgComplexity, candidates } = await getCandidatesForStorybook(
4878
+ files,
4879
+ sampleSize
4880
+ );
4881
+ return {
4882
+ analyzedCount,
4883
+ avgComplexity,
4884
+ candidates,
4885
+ globMatchCount
4886
+ };
4887
+ } catch {
4888
+ return {
4889
+ candidates: [],
4890
+ error: "Failed to find candidates",
4891
+ globMatchCount
4892
+ };
4893
+ }
4894
+ }
4895
+
4896
+ // src/core-server/utils/ghost-stories/run-story-tests.ts
4897
+ import { existsSync as existsSync4 } from "node:fs";
4898
+ import { mkdir as mkdir5, readFile as readFile8 } from "node:fs/promises";
4899
+ import { executeCommand, resolvePathInForkbookCache as resolvePathInForkbookCache3 } from "@aussieljk/forkbook/internal/common";
4900
+ import { join as join13 } from "pathe";
4901
+
4902
+ // src/shared/utils/ecosystem-identifier.ts
4903
+ var STYLING_PACKAGES = [
4904
+ "postcss",
4905
+ "tailwindcss",
4906
+ "autoprefixer",
4907
+ "sass",
4908
+ "less",
4909
+ "styled-components",
4910
+ "@stylexjs/*",
4911
+ "bootstrap",
4912
+ "goober",
4913
+ "stylus",
4914
+ "jss",
4915
+ "linaria",
4916
+ "bulma",
4917
+ "aphrodite",
4918
+ "semantic-ui",
4919
+ "foundation-sites",
4920
+ "fela"
4921
+ ], STATE_MANAGEMENT_PACKAGES = [
4922
+ "*redux*",
4923
+ "@reduxjs/*",
4924
+ "zustand",
4925
+ "jotai",
4926
+ "recoil",
4927
+ "mobx*",
4928
+ "valtio",
4929
+ "xstate",
4930
+ "@xstate/*",
4931
+ "effector",
4932
+ "effector-react",
4933
+ "easy-peasy"
4934
+ ];
4935
+ var I18N_PACKAGES = ["*i18n*", "*intl", "@lingui/*"], ROUTER_PACKAGES = [
4936
+ "react-router",
4937
+ "react-router-dom",
4938
+ "react-easy-router",
4939
+ "@remix-run/router",
4940
+ "expo-router",
4941
+ "@tanstack/*-router",
4942
+ "wouter",
4943
+ "@reach/router"
4944
+ ];
4945
+ function globToRegex(pattern) {
4946
+ let regexPattern = pattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*");
4947
+ return new RegExp(`^${regexPattern}$`);
4948
+ }
4949
+ function matchesPackagePattern(dependencyName, patterns) {
4950
+ return patterns.some((pattern) => globToRegex(pattern).test(dependencyName));
4951
+ }
4952
+ function isStateManagementPackage(dependencyName) {
4953
+ return matchesPackagePattern(dependencyName, STATE_MANAGEMENT_PACKAGES);
4954
+ }
4955
+ function isStylingPackage(dependencyName) {
4956
+ return matchesPackagePattern(dependencyName, STYLING_PACKAGES);
4957
+ }
4958
+ function isRouterPackage(dependencyName) {
4959
+ return matchesPackagePattern(dependencyName, ROUTER_PACKAGES);
4960
+ }
4961
+ function isI18nPackage(dependencyName) {
4962
+ return matchesPackagePattern(dependencyName, I18N_PACKAGES);
4963
+ }
4964
+
4965
+ // src/shared/utils/categorize-render-errors.ts
4966
+ var ERROR_CATEGORIES = {
4967
+ MISSING_PROVIDER: "MISSING_PROVIDER",
4968
+ MISSING_STATE_PROVIDER: "MISSING_STATE_PROVIDER",
4969
+ MISSING_ROUTER_PROVIDER: "MISSING_ROUTER_PROVIDER",
4970
+ MISSING_THEME_PROVIDER: "MISSING_THEME_PROVIDER",
4971
+ MISSING_TRANSLATION_PROVIDER: "MISSING_TRANSLATION_PROVIDER",
4972
+ MISSING_PORTAL_ROOT: "MISSING_PORTAL_ROOT",
4973
+ HOOK_USAGE_ERROR: "HOOK_USAGE_ERROR",
4974
+ MODULE_IMPORT_ERROR: "MODULE_IMPORT_ERROR",
4975
+ COMPONENT_RENDER_ERROR: "COMPONENT_RENDER_ERROR",
4976
+ SERVER_COMPONENTS_ERROR: "SERVER_COMPONENTS_ERROR",
4977
+ UNKNOWN_ERROR: "UNKNOWN_ERROR",
4978
+ // Vite related errors
4979
+ DYNAMIC_MODULE_IMPORT_ERROR: "DYNAMIC_MODULE_IMPORT_ERROR",
4980
+ // Vitest test run related errors
4981
+ TEST_FILE_IMPORT_ERROR: "TEST_FILE_IMPORT_ERROR"
4982
+ };
4983
+ function buildErrorContext(message, stack) {
4984
+ let normalizedMessage = message.toLowerCase(), normalizedStack = (stack ?? "").toLowerCase(), stackDeps = /* @__PURE__ */ new Set(), stackLines = normalizedStack.split(`
4985
+ `).filter(Boolean);
4986
+ for (let line of stackLines) {
4987
+ let depMatch = line.match(/\/deps\/([^:]+)\.js/);
4988
+ depMatch && stackDeps.add(depMatch[1]);
4989
+ }
4990
+ return {
4991
+ message,
4992
+ stack,
4993
+ normalizedMessage,
4994
+ normalizedStack,
4995
+ stackDeps
4996
+ };
4997
+ }
4998
+ var CATEGORIZATION_RULES = [
4999
+ {
5000
+ category: ERROR_CATEGORIES.MODULE_IMPORT_ERROR,
5001
+ priority: 100,
5002
+ match: (ctx) => ctx.normalizedMessage.includes("cannot find module") || ctx.normalizedMessage.includes("module not found") || ctx.normalizedMessage.includes("cannot resolve module")
5003
+ },
5004
+ {
5005
+ category: ERROR_CATEGORIES.TEST_FILE_IMPORT_ERROR,
5006
+ priority: 95,
5007
+ match: (ctx) => ctx.normalizedMessage.includes("failed to import test file")
5008
+ },
5009
+ {
5010
+ category: ERROR_CATEGORIES.DYNAMIC_MODULE_IMPORT_ERROR,
5011
+ priority: 95,
5012
+ match: (ctx) => ctx.normalizedMessage.includes("failed to fetch dynamically imported module")
5013
+ },
5014
+ {
5015
+ category: ERROR_CATEGORIES.HOOK_USAGE_ERROR,
5016
+ priority: 90,
5017
+ match: (ctx) => ctx.normalizedMessage.includes("invalid hook call") || ctx.normalizedMessage.includes("rendered more hooks") || ctx.normalizedMessage.includes("hooks can only be called") || ctx.normalizedMessage.includes("too many re-renders") || ctx.normalizedMessage.includes("maximum update depth exceeded") || ctx.normalizedMessage.includes("hook") && ctx.normalizedMessage.includes("function component")
5018
+ },
5019
+ {
5020
+ category: ERROR_CATEGORIES.MISSING_STATE_PROVIDER,
5021
+ priority: 85,
5022
+ match: (ctx) => Array.from(ctx.stackDeps).some(isStateManagementPackage) && (ctx.normalizedMessage.includes("context") || ctx.normalizedMessage.includes("undefined") || ctx.normalizedMessage.includes("null"))
5023
+ },
5024
+ {
5025
+ category: ERROR_CATEGORIES.MISSING_ROUTER_PROVIDER,
5026
+ priority: 85,
5027
+ match: (ctx) => Array.from(ctx.stackDeps).some(isRouterPackage) || ctx.normalizedMessage.includes("usenavigate") || ctx.normalizedMessage.includes("router")
5028
+ },
5029
+ {
5030
+ category: ERROR_CATEGORIES.SERVER_COMPONENTS_ERROR,
5031
+ priority: 85,
5032
+ match: (ctx) => ctx.normalizedMessage.includes("server components") || ctx.normalizedMessage.includes("use client") || ctx.normalizedMessage.includes("async/await") && ctx.normalizedMessage.includes("not supported")
5033
+ },
5034
+ {
5035
+ category: ERROR_CATEGORIES.MISSING_THEME_PROVIDER,
5036
+ priority: 80,
5037
+ match: (ctx) => Array.from(ctx.stackDeps).some(isStylingPackage) && (ctx.normalizedMessage.includes("theme") || ctx.normalizedMessage.includes("undefined")) || ctx.normalizedMessage.includes("usetheme") || ctx.normalizedMessage.includes("theme") && ctx.normalizedMessage.includes("provider")
5038
+ },
5039
+ {
5040
+ category: ERROR_CATEGORIES.MISSING_TRANSLATION_PROVIDER,
5041
+ priority: 80,
5042
+ match: (ctx) => Array.from(ctx.stackDeps).some(isI18nPackage) || ctx.normalizedMessage.includes("i18n") || ctx.normalizedMessage.includes("translation") || ctx.normalizedMessage.includes("locale")
5043
+ },
5044
+ {
5045
+ category: ERROR_CATEGORIES.MISSING_PORTAL_ROOT,
5046
+ priority: 70,
5047
+ match: (ctx) => ctx.normalizedMessage.includes("target container is not a dom element") || ctx.normalizedMessage.includes("portal") && (ctx.normalizedMessage.includes("container") || ctx.normalizedMessage.includes("root"))
5048
+ },
5049
+ {
5050
+ category: ERROR_CATEGORIES.MISSING_PROVIDER,
5051
+ priority: 60,
5052
+ match: (ctx) => ctx.normalizedMessage.includes("use") && ctx.normalizedMessage.includes("provider") || ctx.normalizedMessage.includes("<provider>") || ctx.normalizedMessage.includes("no provider") || ctx.normalizedMessage.includes("without a provider") || (ctx.normalizedMessage.includes("could not find") || ctx.normalizedMessage.includes("missing") || ctx.normalizedMessage.includes("not found")) && ctx.normalizedMessage.includes("context") || ctx.normalizedMessage.includes("context") && (ctx.normalizedMessage.includes("null") || ctx.normalizedMessage.includes("undefined"))
5053
+ },
5054
+ {
5055
+ category: ERROR_CATEGORIES.COMPONENT_RENDER_ERROR,
5056
+ priority: 10,
5057
+ match: (ctx) => ctx.normalizedMessage.includes("cannot read") || ctx.normalizedMessage.includes("is not a function") || ctx.normalizedMessage.includes("is not an object") || ctx.normalizedMessage.includes("is not defined") || ctx.normalizedMessage.includes("element type is invalid") || ctx.normalizedMessage.includes("objects are not valid as a react child") || ctx.normalizedMessage.includes("maximum call stack") || ctx.normalizedMessage.includes("render")
5058
+ }
5059
+ ], RULES = CATEGORIZATION_RULES.sort((a, b) => b.priority - a.priority);
5060
+ function categorizeError(message, stack) {
5061
+ let ctx = buildErrorContext(message, stack), rule = RULES.find((r) => r.match(ctx));
5062
+ if (!rule)
5063
+ return { category: ERROR_CATEGORIES.UNKNOWN_ERROR, matchedDependencies: [] };
5064
+ let matchedDependencies = getMatchedDependencies(rule.category, ctx);
5065
+ return { category: rule.category, matchedDependencies };
5066
+ }
5067
+ function getMatchedDependencies(category, ctx) {
5068
+ switch (category) {
5069
+ case ERROR_CATEGORIES.MISSING_STATE_PROVIDER:
5070
+ return Array.from(ctx.stackDeps).filter(isStateManagementPackage);
5071
+ case ERROR_CATEGORIES.MISSING_ROUTER_PROVIDER:
5072
+ return Array.from(ctx.stackDeps).filter(isRouterPackage);
5073
+ case ERROR_CATEGORIES.MISSING_THEME_PROVIDER:
5074
+ return Array.from(ctx.stackDeps).filter(isStylingPackage);
5075
+ case ERROR_CATEGORIES.MISSING_TRANSLATION_PROVIDER:
5076
+ return Array.from(ctx.stackDeps).filter(isI18nPackage);
5077
+ default:
5078
+ return [];
5079
+ }
5080
+ }
5081
+
5082
+ // src/shared/utils/analyze-test-results.ts
5083
+ function extractCategorizedErrors(testResults) {
5084
+ let failed = testResults.filter((r) => r.status === "FAIL" && r.error), map = /* @__PURE__ */ new Map(), uniqueErrorMessages = /* @__PURE__ */ new Set();
5085
+ for (let r of failed) {
5086
+ let { category, matchedDependencies } = categorizeError(r.error, r.stack);
5087
+ map.has(category) || map.set(category, { count: 0, uniqueErrors: /* @__PURE__ */ new Set(), matchedDependencies: /* @__PURE__ */ new Set() });
5088
+ let data = map.get(category);
5089
+ data.count++, matchedDependencies.forEach((dep) => data.matchedDependencies.add(dep)), uniqueErrorMessages.add(r.error), data.uniqueErrors.add(r.error);
5090
+ }
5091
+ let categorizedErrors = Array.from(map.entries()).reduce(
5092
+ (acc, [category, data]) => (acc[category] = {
5093
+ uniqueCount: data.uniqueErrors.size,
5094
+ count: data.count,
5095
+ matchedDependencies: Array.from(data.matchedDependencies).sort()
5096
+ }, acc),
5097
+ {}
5098
+ );
5099
+ return {
5100
+ totalErrors: failed.length,
5101
+ uniqueErrorCount: uniqueErrorMessages.size,
5102
+ categorizedErrors
5103
+ };
5104
+ }
5105
+ var CSS_CHECK_STORY_ID_SUFFIX = "--css-check";
5106
+ function summarizeResults(results) {
5107
+ let total = results.length, passed = results.filter((r) => r.status === "PASS").length, passedButEmptyRender = results.filter((r) => r.status === "PASS" && r.emptyRender).length, successRate = total > 0 ? parseFloat((passed / total).toFixed(2)) : 0, successRateWithoutEmptyRender = total > 0 ? parseFloat(((passed - passedButEmptyRender) / total).toFixed(2)) : 0, errorClassification = extractCategorizedErrors(results), cssCheckMatch = results.find(
5108
+ (r) => r.storyId.toLowerCase().endsWith(CSS_CHECK_STORY_ID_SUFFIX)
5109
+ ), cssCheck = cssCheckMatch?.status === "PASS" ? "pass" : cssCheckMatch?.status === "FAIL" ? "fail" : "not-run";
5110
+ return {
5111
+ total,
5112
+ passed,
5113
+ passedButEmptyRender,
5114
+ successRate,
5115
+ successRateWithoutEmptyRender,
5116
+ uniqueErrorCount: errorClassification.uniqueErrorCount,
5117
+ categorizedErrors: errorClassification.categorizedErrors,
5118
+ cssCheck
5119
+ };
5120
+ }
5121
+ function analyzeTestResults(results, cumulativeResults) {
5122
+ let run = summarizeResults(results), analysis = {
5123
+ total: run.total,
5124
+ passed: run.passed,
5125
+ passedButEmptyRender: run.passedButEmptyRender,
5126
+ successRate: run.successRate,
5127
+ successRateWithoutEmptyRender: run.successRateWithoutEmptyRender,
5128
+ uniqueErrorCount: run.uniqueErrorCount,
5129
+ categorizedErrors: run.categorizedErrors,
5130
+ cssCheck: run.cssCheck
5131
+ };
5132
+ if (cumulativeResults) {
5133
+ let cumulative = summarizeResults(cumulativeResults);
5134
+ analysis.cumulativeTotal = cumulative.total, analysis.cumulativePassed = cumulative.passed, analysis.cumulativePassedButEmptyRender = cumulative.passedButEmptyRender, analysis.cumulativeSuccessRate = cumulative.successRate, analysis.cumulativeSuccessRateWithoutEmptyRender = cumulative.successRateWithoutEmptyRender, analysis.cumulativeUniqueErrorCount = cumulative.uniqueErrorCount, analysis.cumulativeCategorizedErrors = cumulative.categorizedErrors, analysis.cumulativeCssCheck = cumulative.cssCheck;
5135
+ }
5136
+ return analysis;
5137
+ }
5138
+
5139
+ // src/shared/utils/to-story-test-result.ts
5140
+ var DEBUG_BANNER_RE = /^\n(?:\x1B\[\d+m)?Click to debug\b[^\n]*\n\n/;
5141
+ function extractErrorMessage(message, stack) {
5142
+ return (message ?? "").replace(DEBUG_BANNER_RE, "").split(`
5143
+ `)[0] || stack?.split(`
5144
+ `)[0] || "unknown error";
5145
+ }
5146
+ function detectEmptyRender(reports) {
5147
+ return reports?.some(
5148
+ (report) => report.type === "render-analysis" && report.result?.emptyRender === !0
5149
+ ) ?? !1;
5150
+ }
5151
+ function normalizeStatus(statusRaw) {
5152
+ return statusRaw === "passed" ? "PASS" : statusRaw === "failed" ? "FAIL" : "PENDING";
5153
+ }
5154
+ function toStoryTestResult(input) {
5155
+ if (!input.storyId)
5156
+ return null;
5157
+ let status = normalizeStatus(input.statusRaw), emptyRender = status === "PASS" && detectEmptyRender(input.reports), error, stack;
5158
+ if (input.errors && input.errors.length > 0) {
5159
+ let firstError = input.errors[0];
5160
+ error = extractErrorMessage(firstError.message, firstError.stack), stack = firstError.stack ?? firstError.message;
5161
+ }
5162
+ return {
5163
+ storyId: input.storyId,
5164
+ status,
5165
+ error,
5166
+ stack,
5167
+ emptyRender: emptyRender || void 0
5168
+ };
5169
+ }
5170
+
5171
+ // src/core-server/utils/ghost-stories/parse-vitest-report.ts
5172
+ function parseVitestResults(report) {
5173
+ let storyTestResults = [];
5174
+ for (let testSuite of report.testResults)
5175
+ for (let assertion of testSuite.assertionResults) {
5176
+ let result = toStoryTestResult({
5177
+ storyId: assertion.meta?.storyId ?? assertion.fullName,
5178
+ statusRaw: assertion.status,
5179
+ reports: assertion.meta?.reports,
5180
+ errors: assertion.failureMessages?.map((message) => ({ stack: message }))
5181
+ });
5182
+ result && storyTestResults.push(result);
5183
+ }
5184
+ return {
5185
+ summary: analyzeTestResults(storyTestResults)
5186
+ };
5187
+ }
5188
+
5189
+ // src/core-server/utils/ghost-stories/run-story-tests.ts
5190
+ async function runStoryTests(componentFilePaths, options) {
5191
+ let cwd = options?.cwd;
5192
+ try {
5193
+ let cacheDir = resolvePathInForkbookCache3("story-tests");
5194
+ await mkdir5(cacheDir, { recursive: !0 });
5195
+ let timestamp = Date.now(), outputFile = join13(cacheDir, `test-results-${timestamp}.json`), startTime = Date.now(), testFailureMessage;
5196
+ try {
5197
+ await executeCommand({
5198
+ command: "npx",
5199
+ args: [
5200
+ "vitest",
5201
+ "run",
5202
+ "--reporter=json",
5203
+ "--testTimeout=1000",
5204
+ `--outputFile=${outputFile}`,
5205
+ ...componentFilePaths
5206
+ ],
5207
+ cwd,
5208
+ stdio: "pipe",
5209
+ env: {
5210
+ FORKBOOK_INTERNAL_TEST_RUN: "1",
5211
+ ...options?.ghostRun ? { FORKBOOK_COMPONENT_PATHS: componentFilePaths.join(";") } : {}
5212
+ }
5213
+ });
5214
+ } catch (error) {
5215
+ let errorMessage = (error.stderr || String(error) || "").toLowerCase();
5216
+ errorMessage.includes("browsertype.launch") ? testFailureMessage = "Playwright is not installed" : errorMessage.includes("startup error") ? testFailureMessage = "Startup Error" : errorMessage.includes("no tests found") ? testFailureMessage = "No tests found" : errorMessage.includes("test timeout") ? testFailureMessage = "Test timeout" : errorMessage.includes("react-native-web") ? testFailureMessage = "React Native Web error" : errorMessage.includes("unhandled rejection") && (testFailureMessage = "Unhandled Rejection");
5217
+ }
5218
+ let duration = Date.now() - startTime;
5219
+ if (testFailureMessage)
5220
+ return {
5221
+ duration,
5222
+ runError: testFailureMessage
5223
+ };
5224
+ if (!existsSync4(outputFile))
5225
+ return {
5226
+ duration,
5227
+ runError: "JSON report not found"
5228
+ };
5229
+ let vitestReport;
5230
+ try {
5231
+ let resultsJson = await readFile8(outputFile, "utf8");
5232
+ vitestReport = JSON.parse(resultsJson);
5233
+ } catch {
5234
+ return {
5235
+ duration,
5236
+ runError: "Failed to read or parse JSON report"
5237
+ };
5238
+ }
5239
+ return !vitestReport.testResults || vitestReport.testResults.length === 0 ? {
5240
+ duration,
5241
+ runError: "No tests found"
5242
+ } : { ...parseVitestResults(vitestReport), duration };
5243
+ } catch {
5244
+ return {
5245
+ runError: "Uncaught error running story tests",
5246
+ duration: 0
5247
+ };
5248
+ }
5249
+ }
5250
+
5251
+ // src/core-server/utils/skills/addon-a11y.ts
5252
+ async function isAddonA11yEnabled(options) {
5253
+ try {
5254
+ return await options.presets.apply("isAddonA11yEnabled", !1);
5255
+ } catch {
5256
+ return !1;
5257
+ }
5258
+ }
5259
+
5260
+ // src/core-server/utils/skills/addon-vitest.ts
5261
+ async function isAddonVitestEnabled(options) {
5262
+ try {
5263
+ return await options.presets.apply("isAddonVitestEnabled", !1);
5264
+ } catch {
5265
+ return !1;
5266
+ }
5267
+ }
5268
+
5269
+ // src/core-server/utils/skills/manifest-status.ts
5270
+ var hasComponentManifestFeature = (features) => !!(features?.componentsManifest ?? features?.experimentalComponentsManifest), isDocgenServerMode = (features) => !!(features?.docgenServer && features?.componentsManifest), getManifestStatus = async (options) => {
5271
+ let [
5272
+ features,
5273
+ manifests,
5274
+ // Added for backwards compatibility with Forkbook versions prior to v10.2.0-alpha.10
5275
+ // Should be removed once support for Forkbook version < 10.2.0 is dropped
5276
+ legacyComponentManifestGenerator
5277
+ ] = await Promise.all([
5278
+ options.presets.apply("features"),
5279
+ options.presets.apply("experimental_manifests", void 0, {
5280
+ manifestEntries: []
5281
+ }),
5282
+ options.presets.apply("experimental_componentManifestGenerator")
5283
+ ]), hasFeatureFlag = hasComponentManifestFeature(features), docgenServer = isDocgenServerMode(features), hasManifests = docgenServer || manifests && "components" in manifests || !!legacyComponentManifestGenerator;
5284
+ return {
5285
+ available: hasFeatureFlag && hasManifests,
5286
+ hasManifests,
5287
+ hasFeatureFlag,
5288
+ docgenServer
5289
+ };
5290
+ };
5291
+
5292
+ // src/core-server/utils/skills/availability.ts
5293
+ function getEffectiveToolAvailability(availability, { multiSource = !1 } = {}) {
5294
+ return multiSource ? {
5295
+ ...availability,
5296
+ docsEnabled: !0,
5297
+ docsEnabledForCli: !0,
5298
+ docsHasManifests: !0,
5299
+ docsFeatureEnabled: !0
5300
+ } : availability;
5301
+ }
5302
+ async function isModuleGraphSupported() {
5303
+ try {
5304
+ return getService("core/module-graph", { internal: !0 }) !== void 0;
5305
+ } catch {
5306
+ return !1;
5307
+ }
5308
+ }
5309
+ async function getToolAvailability(options) {
5310
+ let [moduleGraphSupported, manifestStatus, addonVitestEnabled, a11yEnabled] = await Promise.all(
5311
+ [
5312
+ isModuleGraphSupported(),
5313
+ getManifestStatus(options),
5314
+ isAddonVitestEnabled(options),
5315
+ isAddonA11yEnabled(options)
5316
+ ]
5317
+ );
5318
+ return {
5319
+ moduleGraphSupported,
5320
+ docsEnabled: manifestStatus.available,
5321
+ docsEnabledForCli: manifestStatus.hasManifests,
5322
+ docsHasManifests: manifestStatus.hasManifests,
5323
+ docsFeatureEnabled: manifestStatus.hasFeatureFlag,
5324
+ testSupported: addonVitestEnabled,
5325
+ a11yEnabled,
5326
+ docgenServer: manifestStatus.docgenServer
5327
+ };
5328
+ }
5329
+
5330
+ // src/core-server/utils/skills/inputs.ts
5331
+ import { relative as relative8 } from "node:path";
5332
+ var isTypeScriptFile = (path) => /\.[cm]?tsx?$/.test(path);
5333
+ async function resolvePreview(configDir = defaultConfigDir()) {
5334
+ let previewPath = findConfigFile("preview", configDir), typescript = isTypeScriptFile(previewPath ?? findConfigFile("main", configDir) ?? ""), path = previewPath ?? `${configDir}/preview.${typescript ? "ts" : "js"}`, csfFactories = !1;
5335
+ if (previewPath)
5336
+ try {
5337
+ csfFactories = isCsfFactoryPreview(await readConfig(previewPath));
5338
+ } catch {
5339
+ }
5340
+ return {
5341
+ csfFactories,
5342
+ typescript,
5343
+ previewFile: relative8(process.cwd(), path).replaceAll("\\", "/") || path
5344
+ };
5345
+ }
5346
+ async function resolveSkillInputs(options) {
5347
+ let [availability, frameworkPreset, preview] = await Promise.all([
5348
+ getToolAvailability(options),
5349
+ options.presets.apply("framework"),
5350
+ resolvePreview(options.configDir)
5351
+ ]), framework = extractFrameworkPackageName(
5352
+ typeof frameworkPreset == "string" ? frameworkPreset : frameworkPreset?.name ?? ""
5353
+ );
5354
+ return { ...availability, ...preview, framework, renderer: frameworkToRendererMap[framework] };
5355
+ }
4095
5356
  export {
4096
5357
  ChangeDetectionFailureError,
4097
5358
  ChangeDetectionService,
4098
5359
  ChangeDetectionUnavailableError,
5360
+ DEFAULT_STATIC_OUTPUT_DIR,
4099
5361
  MDX_SERVICE_ID,
5362
+ RequestBodyTooLargeError,
4100
5363
  StoryIndexGenerator,
4101
5364
  Tag,
4102
5365
  analyzeMdx,
@@ -4119,7 +5382,7 @@ export {
4119
5382
  getChangeDetectionReadiness as experimental_getChangeDetectionReadiness,
4120
5383
  getStatusStoreByTypeId as experimental_getStatusStore,
4121
5384
  getTestProviderStoreById as experimental_getTestProviderStore,
4122
- loadStorybook as experimental_loadStorybook,
5385
+ loadForkbook as experimental_loadForkbook,
4123
5386
  registerService as experimental_registerService,
4124
5387
  resetChangeDetectionReadiness as experimental_resetChangeDetectionReadiness,
4125
5388
  resetServicesPresetOnce as experimental_resetServicesPresetOnce,
@@ -4144,6 +5407,7 @@ export {
4144
5407
  universalTestProviderStore as internal_universalTestProviderStore,
4145
5408
  isAddonA11yEnabled,
4146
5409
  isAddonVitestEnabled,
5410
+ isCrossSiteRequest,
4147
5411
  isModuleGraphSupported,
4148
5412
  isValidHost,
4149
5413
  listServices,
@@ -4153,11 +5417,14 @@ export {
4153
5417
  mdxQueryStaticPath,
4154
5418
  mdxStaticStorePath,
4155
5419
  prepareHeadlessUniversalStores,
5420
+ readRequestBody,
4156
5421
  registerToolset,
4157
5422
  resolveChangeDetectionAdapter,
4158
5423
  resolveSkillInputs,
5424
+ resolveStaticOutputDir,
4159
5425
  reviewToolset,
4160
5426
  runStoryTests,
5427
+ sendPayloadTooLarge,
4161
5428
  sendTelemetryError,
4162
5429
  storyInputArraySchema,
4163
5430
  toStoryTestResult,