@aussieljk/forkbook 0.0.0-stage → 0.0.1-2

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 (598) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +77 -2
  3. package/assets/addon-vitest/templates/vitest.config.4.template.ts +36 -0
  4. package/assets/browser/favicon-wrapper.svg +46 -0
  5. package/assets/browser/favicon.svg +1 -0
  6. package/assets/browser/nunito-sans-bold-italic.woff2 +0 -0
  7. package/assets/browser/nunito-sans-bold.woff2 +0 -0
  8. package/assets/browser/nunito-sans-italic.woff2 +0 -0
  9. package/assets/browser/nunito-sans-regular.woff2 +0 -0
  10. package/assets/builder-vite/iframe.html +99 -0
  11. package/assets/create/rendererAssets/.eslintrc.json +16 -0
  12. package/assets/create/rendererAssets/common/Configure.mdx +388 -0
  13. package/assets/create/rendererAssets/common/assets/accessibility.png +0 -0
  14. package/assets/create/rendererAssets/common/assets/accessibility.svg +1 -0
  15. package/assets/create/rendererAssets/common/assets/addon-library.png +0 -0
  16. package/assets/create/rendererAssets/common/assets/assets.png +0 -0
  17. package/assets/create/rendererAssets/common/assets/avif-test-image.avif +0 -0
  18. package/assets/create/rendererAssets/common/assets/context.png +0 -0
  19. package/assets/create/rendererAssets/common/assets/discord.svg +1 -0
  20. package/assets/create/rendererAssets/common/assets/docs.png +0 -0
  21. package/assets/create/rendererAssets/common/assets/figma-plugin.png +0 -0
  22. package/assets/create/rendererAssets/common/assets/github.svg +1 -0
  23. package/assets/create/rendererAssets/common/assets/share.png +0 -0
  24. package/assets/create/rendererAssets/common/assets/styling.png +0 -0
  25. package/assets/create/rendererAssets/common/assets/testing.png +0 -0
  26. package/assets/create/rendererAssets/common/assets/theming.png +0 -0
  27. package/assets/create/rendererAssets/common/assets/tutorials.svg +1 -0
  28. package/assets/create/rendererAssets/common/assets/youtube.svg +1 -0
  29. package/assets/create/rendererAssets/common/button.css +30 -0
  30. package/assets/create/rendererAssets/common/header.css +32 -0
  31. package/assets/create/rendererAssets/common/page.css +68 -0
  32. package/assets/create/templates/react-native/index.expo.js +20 -0
  33. package/assets/create/templates/react-native/index.js +25 -0
  34. package/assets/docs/addon-backgrounds.gif +0 -0
  35. package/assets/docs/addon-controls-args-annotated.png +0 -0
  36. package/assets/docs/addon-controls-args-background-color.png +0 -0
  37. package/assets/docs/addon-controls-args-background-string.png +0 -0
  38. package/assets/docs/addon-controls-args-docs.png +0 -0
  39. package/assets/docs/addon-controls-args-logging.png +0 -0
  40. package/assets/docs/addon-controls-args-no-annotation.png +0 -0
  41. package/assets/docs/addon-controls-args-reflow-slider.png +0 -0
  42. package/assets/docs/addon-controls-args-reflow.png +0 -0
  43. package/assets/docs/addon-controls-args-template.png +0 -0
  44. package/assets/docs/addon-controls-expanded.png +0 -0
  45. package/assets/docs/addon-controls-hero.gif +0 -0
  46. package/assets/docs/addon-controls-install.png +0 -0
  47. package/assets/docs/hero.gif +0 -0
  48. package/assets/docs/highlight.png +0 -0
  49. package/assets/docs/message-reference.png +0 -0
  50. package/assets/docs/viewport.png +0 -0
  51. package/assets/react-native/metro-env.d.ts +69 -0
  52. package/assets/server/addon.tsconfig.json +6 -0
  53. package/assets/server/base-preview-body.html +116 -0
  54. package/assets/server/base-preview-head.html +494 -0
  55. package/assets/server/openBrowser.applescript +94 -0
  56. package/assets/server/template.ejs +87 -0
  57. package/dist/.build-stamp +0 -0
  58. package/dist/_browser-chunks/Color-PCLE2J36.js +1025 -0
  59. package/dist/_browser-chunks/DocsRenderer-JXND3PVQ.js +10 -0
  60. package/dist/_browser-chunks/WithTooltip-XSQFTBMB.js +1619 -0
  61. package/dist/_browser-chunks/chunk-2JDQ35OA.js +247 -0
  62. package/dist/_browser-chunks/chunk-2JT76G3E.js +104 -0
  63. package/dist/_browser-chunks/chunk-2MEPHP35.js +17 -0
  64. package/dist/_browser-chunks/chunk-2SCZVUKW.js +24 -0
  65. package/dist/_browser-chunks/chunk-46Z7NGAS.js +41 -0
  66. package/dist/_browser-chunks/chunk-4ATQOMJB.js +30 -0
  67. package/dist/_browser-chunks/chunk-52CW7FF7.js +49 -0
  68. package/dist/_browser-chunks/chunk-5I7E4GMO.js +62 -0
  69. package/dist/_browser-chunks/chunk-5P4QA6MY.js +20 -0
  70. package/dist/_browser-chunks/chunk-5WMXI5GW.js +816 -0
  71. package/dist/_browser-chunks/chunk-66OCZ54D.js +2604 -0
  72. package/dist/_browser-chunks/chunk-6SXYJQST.js +253 -0
  73. package/dist/_browser-chunks/chunk-AYRF6EJB.js +36 -0
  74. package/dist/_browser-chunks/chunk-B4AUNNU4.js +156 -0
  75. package/dist/_browser-chunks/chunk-BCP2FFXF.js +369 -0
  76. package/dist/_browser-chunks/chunk-C3D4HEFY.js +3396 -0
  77. package/dist/_browser-chunks/chunk-CFAOWGL7.js +43 -0
  78. package/dist/_browser-chunks/chunk-CFWWCCZV.js +223 -0
  79. package/dist/_browser-chunks/chunk-CNED6RYH.js +18 -0
  80. package/dist/_browser-chunks/chunk-DRQKCCAG.js +136 -0
  81. package/dist/_browser-chunks/chunk-ECQ75MKQ.js +0 -0
  82. package/dist/_browser-chunks/chunk-EIYAKDGP.js +302 -0
  83. package/dist/_browser-chunks/chunk-ENKK74N4.js +12 -0
  84. package/dist/_browser-chunks/chunk-FENFYI4X.js +698 -0
  85. package/dist/_browser-chunks/chunk-FJGWSWL5.js +155 -0
  86. package/dist/_browser-chunks/chunk-FVSEPWWX.js +2810 -0
  87. package/dist/_browser-chunks/chunk-GNZY6LOW.js +10116 -0
  88. package/dist/_browser-chunks/chunk-IE4ULIOQ.js +14 -0
  89. package/dist/_browser-chunks/chunk-IMSF75WX.js +42 -0
  90. package/dist/_browser-chunks/chunk-IWQGIXJS.js +14 -0
  91. package/dist/_browser-chunks/chunk-JMC7AIKT.js +108 -0
  92. package/dist/_browser-chunks/chunk-JPUOQJUI.js +8 -0
  93. package/dist/_browser-chunks/chunk-JSBKXXXF.js +218 -0
  94. package/dist/_browser-chunks/chunk-JWSKPMPC.js +73 -0
  95. package/dist/_browser-chunks/chunk-JYVGARBG.js +2943 -0
  96. package/dist/_browser-chunks/chunk-KBK7GKBN.js +35 -0
  97. package/dist/_browser-chunks/chunk-KQ7CRO2B.js +108 -0
  98. package/dist/_browser-chunks/chunk-LAWXTSXK.js +18 -0
  99. package/dist/_browser-chunks/chunk-LE2LTDW3.js +14 -0
  100. package/dist/_browser-chunks/chunk-LEVSOOLQ.js +48 -0
  101. package/dist/_browser-chunks/chunk-LV5PIKV4.js +93 -0
  102. package/dist/_browser-chunks/chunk-MDOL7KML.js +56 -0
  103. package/dist/_browser-chunks/chunk-MFMDGWP6.js +34 -0
  104. package/dist/_browser-chunks/chunk-MLBOOZL4.js +67 -0
  105. package/dist/_browser-chunks/chunk-NQUD4B7H.js +91 -0
  106. package/dist/_browser-chunks/chunk-NULBREPZ.js +43 -0
  107. package/dist/_browser-chunks/chunk-NZMVUW5T.js +7 -0
  108. package/dist/_browser-chunks/chunk-OD6IBQCC.js +117 -0
  109. package/dist/_browser-chunks/chunk-ODVJ3XZJ.js +157 -0
  110. package/dist/_browser-chunks/chunk-OQWFVDIN.js +386 -0
  111. package/dist/_browser-chunks/chunk-OVH3USFB.js +20 -0
  112. package/dist/_browser-chunks/chunk-OZZPSYQR.js +14 -0
  113. package/dist/_browser-chunks/chunk-P6PK47TQ.js +1970 -0
  114. package/dist/_browser-chunks/chunk-PFRNG3UC.js +22 -0
  115. package/dist/_browser-chunks/chunk-PJSMZ27A.js +13 -0
  116. package/dist/_browser-chunks/chunk-QC4HFS6K.js +41 -0
  117. package/dist/_browser-chunks/chunk-QDXFODK4.js +274 -0
  118. package/dist/_browser-chunks/chunk-RBCHTR7C.js +28 -0
  119. package/dist/_browser-chunks/chunk-RMYQ3QN3.js +294 -0
  120. package/dist/_browser-chunks/chunk-RNTIV5CE.js +411 -0
  121. package/dist/_browser-chunks/chunk-RSPAQWVJ.js +80 -0
  122. package/dist/_browser-chunks/chunk-S6TK43XQ.js +836 -0
  123. package/dist/_browser-chunks/chunk-SC67XZST.js +18 -0
  124. package/dist/_browser-chunks/chunk-SFVA4SBT.js +683 -0
  125. package/dist/_browser-chunks/chunk-SZYFOQMT.js +25 -0
  126. package/dist/_browser-chunks/chunk-TBJCJXK4.js +18 -0
  127. package/dist/_browser-chunks/chunk-UMDO3KB7.js +205 -0
  128. package/dist/_browser-chunks/chunk-V2G23FV7.js +11 -0
  129. package/dist/_browser-chunks/chunk-V5M7Q4HT.js +88 -0
  130. package/dist/_browser-chunks/chunk-W5M6NPS3.js +198 -0
  131. package/dist/_browser-chunks/chunk-W7NE2JXW.js +84 -0
  132. package/dist/_browser-chunks/chunk-WGVAAM43.js +1110 -0
  133. package/dist/_browser-chunks/chunk-WHQRNHXD.js +8 -0
  134. package/dist/_browser-chunks/chunk-WOSOWBCA.js +12 -0
  135. package/dist/_browser-chunks/chunk-WZ7KR7SH.js +85 -0
  136. package/dist/_browser-chunks/chunk-YEKO6BHJ.js +20 -0
  137. package/dist/_browser-chunks/chunk-YI2IBIQS.js +7 -0
  138. package/dist/_browser-chunks/chunk-YTIT5NA5.js +1966 -0
  139. package/dist/_browser-chunks/chunk-ZEHRUHTA.js +6 -0
  140. package/dist/_browser-chunks/chunk-ZTQ5MEJ5.js +203 -0
  141. package/dist/_browser-chunks/matchers-YLBYSYAF.js +1263 -0
  142. package/dist/_browser-chunks/react-dom-client-4OHE3QDV.js +9 -0
  143. package/dist/_node-chunks/attached-runtime-I2G4WLJI.js +282 -0
  144. package/dist/_node-chunks/builder-manager-VVHYQXCH.js +1661 -0
  145. package/dist/_node-chunks/chunk-2BUPBPFB.js +82 -0
  146. package/dist/_node-chunks/chunk-2DSIDINN.js +884 -0
  147. package/dist/_node-chunks/chunk-2RU7BKEW.js +23 -0
  148. package/dist/_node-chunks/chunk-34EO2PUT.js +26 -0
  149. package/dist/_node-chunks/chunk-3BKIBF5S.js +3008 -0
  150. package/dist/_node-chunks/chunk-3SDUYDXH.js +98 -0
  151. package/dist/_node-chunks/chunk-3T4ZSNPH.js +662 -0
  152. package/dist/_node-chunks/chunk-3W7F2B7P.js +79 -0
  153. package/dist/_node-chunks/chunk-3Y6AAY5H.js +80 -0
  154. package/dist/_node-chunks/chunk-42UWAGPW.js +1193 -0
  155. package/dist/_node-chunks/chunk-4FEANXWU.js +1986 -0
  156. package/dist/_node-chunks/chunk-5DQFEZEA.js +40 -0
  157. package/dist/_node-chunks/chunk-6KEHV53S.js +1218 -0
  158. package/dist/_node-chunks/chunk-6LMWA44H.js +3837 -0
  159. package/dist/_node-chunks/chunk-6YKBRP72.js +20 -0
  160. package/dist/_node-chunks/chunk-7GUDZVRQ.js +110 -0
  161. package/dist/_node-chunks/chunk-B5J7Q7J4.js +21 -0
  162. package/dist/_node-chunks/chunk-BS2WMZMR.js +90 -0
  163. package/dist/_node-chunks/chunk-BSKFCWQD.js +47 -0
  164. package/dist/_node-chunks/chunk-BXVYT7SB.js +36 -0
  165. package/dist/_node-chunks/chunk-CCOTJ4FC.js +688 -0
  166. package/dist/_node-chunks/chunk-CQKMLL5J.js +33 -0
  167. package/dist/_node-chunks/chunk-CXRU72ET.js +63 -0
  168. package/dist/_node-chunks/chunk-DC7DKR5K.js +20 -0
  169. package/dist/_node-chunks/chunk-DHJFTB4K.js +25 -0
  170. package/dist/_node-chunks/chunk-DUR55DJJ.js +1094 -0
  171. package/dist/_node-chunks/chunk-E6YESGLX.js +7032 -0
  172. package/dist/_node-chunks/chunk-EHUNOMDD.js +52345 -0
  173. package/dist/_node-chunks/chunk-ET7PWEO7.js +298 -0
  174. package/dist/_node-chunks/chunk-EWOX7HPJ.js +20 -0
  175. package/dist/_node-chunks/chunk-F3ZFKBHY.js +844 -0
  176. package/dist/_node-chunks/chunk-FK7KGTV7.js +26 -0
  177. package/dist/_node-chunks/chunk-FPZB5OI7.js +35 -0
  178. package/dist/_node-chunks/chunk-FW2HQUBQ.js +25 -0
  179. package/dist/_node-chunks/chunk-FY6UXW6G.js +11 -0
  180. package/dist/_node-chunks/chunk-GEFQN7K3.js +499 -0
  181. package/dist/_node-chunks/chunk-GRBLDJCR.js +989 -0
  182. package/dist/_node-chunks/chunk-H32DYT6P.js +87 -0
  183. package/dist/_node-chunks/chunk-H4PPVMP5.js +23 -0
  184. package/dist/_node-chunks/chunk-HMP2G23X.js +25 -0
  185. package/dist/_node-chunks/chunk-ICPBH3E7.js +59 -0
  186. package/dist/_node-chunks/chunk-IDEL2J23.js +23 -0
  187. package/dist/_node-chunks/chunk-IK4FGZLR.js +223 -0
  188. package/dist/_node-chunks/chunk-JDXXX6LB.js +68 -0
  189. package/dist/_node-chunks/chunk-JGGFYIG5.js +5468 -0
  190. package/dist/_node-chunks/chunk-JPAZLYJ3.js +29 -0
  191. package/dist/_node-chunks/chunk-JZOO7GGC.js +48 -0
  192. package/dist/_node-chunks/chunk-KISMCCP5.js +4744 -0
  193. package/dist/_node-chunks/chunk-LCK4ZQKG.js +115 -0
  194. package/dist/_node-chunks/chunk-LO56I6E2.js +132 -0
  195. package/dist/_node-chunks/chunk-LXBD4UL4.js +104 -0
  196. package/dist/_node-chunks/chunk-MA24JW6C.js +7162 -0
  197. package/dist/_node-chunks/chunk-MK2KYAI6.js +5414 -0
  198. package/dist/_node-chunks/chunk-NDWKJ4CL.js +2102 -0
  199. package/dist/_node-chunks/chunk-NIBT7XDZ.js +168 -0
  200. package/dist/_node-chunks/chunk-NPO45IMH.js +33 -0
  201. package/dist/_node-chunks/chunk-OISX4AGQ.js +414 -0
  202. package/dist/_node-chunks/chunk-OUW6R7C3.js +26 -0
  203. package/dist/_node-chunks/chunk-OWNFOGTA.js +194 -0
  204. package/dist/_node-chunks/chunk-Q7QNUM5H.js +49 -0
  205. package/dist/_node-chunks/chunk-QEQLR22M.js +1877 -0
  206. package/dist/_node-chunks/chunk-RRN2V55B.js +45 -0
  207. package/dist/_node-chunks/chunk-RWFIFGO5.js +144 -0
  208. package/dist/_node-chunks/chunk-RXNJDRGO.js +209 -0
  209. package/dist/_node-chunks/chunk-RZMQ7S3L.js +92 -0
  210. package/dist/_node-chunks/chunk-SIEXZVCR.js +51 -0
  211. package/dist/_node-chunks/chunk-SLWQNBGO.js +2034 -0
  212. package/dist/_node-chunks/chunk-SVTBJ7Q3.js +35 -0
  213. package/dist/_node-chunks/chunk-SWO5CDYU.js +32 -0
  214. package/dist/_node-chunks/chunk-TD5PLLQG.js +121 -0
  215. package/dist/_node-chunks/chunk-TEQGGSP7.js +33 -0
  216. package/dist/_node-chunks/chunk-TFCEV2XX.js +155 -0
  217. package/dist/_node-chunks/chunk-TFEWM4E3.js +1073 -0
  218. package/dist/_node-chunks/chunk-TINO74G5.js +21 -0
  219. package/dist/_node-chunks/chunk-TNJIXE37.js +40 -0
  220. package/dist/_node-chunks/chunk-TWI4GVH7.js +19 -0
  221. package/dist/_node-chunks/chunk-U5W53R2J.js +1011 -0
  222. package/dist/_node-chunks/chunk-UBOGWBEA.js +148 -0
  223. package/dist/_node-chunks/chunk-UMUBKI6E.js +3787 -0
  224. package/dist/_node-chunks/chunk-UVINFLGY.js +56 -0
  225. package/dist/_node-chunks/chunk-V2DY426G.js +1133 -0
  226. package/dist/_node-chunks/chunk-VLOXOXXE.js +45 -0
  227. package/dist/_node-chunks/chunk-W4OMYLSP.js +1297 -0
  228. package/dist/_node-chunks/chunk-WAXVSN3O.js +18 -0
  229. package/dist/_node-chunks/chunk-WCULS5TP.js +3767 -0
  230. package/dist/_node-chunks/chunk-WNZ2UMFM.js +153 -0
  231. package/dist/_node-chunks/chunk-WZJF2OUH.js +74 -0
  232. package/dist/_node-chunks/chunk-XGIUVY52.js +611 -0
  233. package/dist/_node-chunks/chunk-XHL2LVBM.js +415 -0
  234. package/dist/_node-chunks/chunk-XI6B6P47.js +59 -0
  235. package/dist/_node-chunks/chunk-XLP2ZKXV.js +60 -0
  236. package/dist/_node-chunks/chunk-YCMRA6RX.js +95 -0
  237. package/dist/_node-chunks/chunk-YZFWBA5L.js +2700 -0
  238. package/dist/_node-chunks/chunk-ZMAMXQKP.js +4731 -0
  239. package/dist/_node-chunks/chunk-ZWBCQ4MJ.js +110 -0
  240. package/dist/_node-chunks/dist-VTSTZKUB.js +16 -0
  241. package/dist/_node-chunks/globby-OEMHPBFY.js +2884 -0
  242. package/dist/_node-chunks/jiti-NFX6UU74.js +3848 -0
  243. package/dist/_node-chunks/lib-MDVARD7W.js +366 -0
  244. package/dist/_node-chunks/local-runtime-NTKIN2QT.js +78 -0
  245. package/dist/_node-chunks/mdx-plugin-MWISDWDQ.js +5680 -0
  246. package/dist/_node-chunks/monorepo-LIRFMQXE.js +121 -0
  247. package/dist/_node-chunks/monorepo-optimized-tests-relaxed-limits-no-story-deletion-CPDW4XTW.js +121 -0
  248. package/dist/_node-chunks/optimized-tests-HDOLR3EY.js +22 -0
  249. package/dist/_node-chunks/pattern-copy-play-EKHIUAU2.js +807 -0
  250. package/dist/_node-chunks/postinstallAddon-GYGMWDL6.js +20 -0
  251. package/dist/_node-chunks/rehype-external-links-BUN3HUCO.js +121 -0
  252. package/dist/_node-chunks/rehype-slug-PLADX223.js +52 -0
  253. package/dist/_node-chunks/relaxed-limits-GBHW6KIQ.js +117 -0
  254. package/dist/_node-chunks/run-KDTIZNSY.js +103 -0
  255. package/dist/_node-chunks/run-NL66VTNR.js +4532 -0
  256. package/dist/_node-chunks/session-id-KIIVOQLR.js +23 -0
  257. package/dist/_node-chunks/setup-MGC7BQO6.js +278 -0
  258. package/dist/_node-chunks/vitest.config.4.template-JH2THZFG.js +54 -0
  259. package/dist/actions/decorator.d.ts +7 -0
  260. package/dist/actions/decorator.js +43 -0
  261. package/dist/actions/index.d.ts +67 -0
  262. package/dist/actions/index.js +28 -0
  263. package/dist/addon-a11y/index.d.ts +52 -0
  264. package/dist/addon-a11y/index.js +16 -0
  265. package/dist/addon-a11y/manager.js +1429 -0
  266. package/dist/addon-a11y/preset.js +18 -0
  267. package/dist/addon-a11y/preview.d.ts +17 -0
  268. package/dist/addon-a11y/preview.js +15 -0
  269. package/dist/addon-docs/blocks.d.ts +1061 -0
  270. package/dist/addon-docs/blocks.js +2461 -0
  271. package/dist/addon-docs/index.d.ts +236 -0
  272. package/dist/addon-docs/index.js +16 -0
  273. package/dist/addon-docs/manager.js +90 -0
  274. package/dist/addon-docs/mdx-react-shim.d.ts +1 -0
  275. package/dist/addon-docs/mdx-react-shim.js +2 -0
  276. package/dist/addon-docs/preset.js +378 -0
  277. package/dist/addon-docs/preview.d.ts +4 -0
  278. package/dist/addon-docs/preview.js +7 -0
  279. package/dist/addon-links/index.d.ts +22 -0
  280. package/dist/addon-links/index.js +20 -0
  281. package/dist/addon-links/manager.js +14 -0
  282. package/dist/addon-links/preview.d.ts +6 -0
  283. package/dist/addon-links/preview.js +9 -0
  284. package/dist/addon-links/react/index.d.ts +25 -0
  285. package/dist/addon-links/react/index.js +52 -0
  286. package/dist/addon-mcp/preset.js +1345 -0
  287. package/dist/addon-mcp/preview.js +29 -0
  288. package/dist/addon-mcp/tools/preview-stories/preview-stories-app-script.js +1153 -0
  289. package/dist/addon-ondevice-actions/index.d.ts +4 -0
  290. package/dist/addon-ondevice-actions/index.js +7 -0
  291. package/dist/addon-ondevice-actions/register.js +7 -0
  292. package/dist/addon-ondevice-controls/index.d.ts +6 -0
  293. package/dist/addon-ondevice-controls/index.js +14 -0
  294. package/dist/addon-ondevice-controls/register.js +10 -0
  295. package/dist/addon-pseudo-states/index.d.ts +35 -0
  296. package/dist/addon-pseudo-states/index.js +15 -0
  297. package/dist/addon-pseudo-states/manager.js +53 -0
  298. package/dist/addon-pseudo-states/preview.d.ts +9 -0
  299. package/dist/addon-pseudo-states/preview.js +10 -0
  300. package/dist/addon-themes/index.d.ts +80 -0
  301. package/dist/addon-themes/index.js +104 -0
  302. package/dist/addon-themes/manager.js +97 -0
  303. package/dist/addon-themes/postinstall.js +33 -0
  304. package/dist/addon-themes/preview.d.ts +6 -0
  305. package/dist/addon-themes/preview.js +8 -0
  306. package/dist/addon-vitest/constants.d.ts +132 -0
  307. package/dist/addon-vitest/constants.js +66 -0
  308. package/dist/addon-vitest/index.d.ts +4 -0
  309. package/dist/addon-vitest/index.js +8 -0
  310. package/dist/addon-vitest/manager.js +665 -0
  311. package/dist/addon-vitest/node/coverage-reporter.js +1284 -0
  312. package/dist/addon-vitest/node/vitest.js +674 -0
  313. package/dist/addon-vitest/postinstall.js +24 -0
  314. package/dist/addon-vitest/preset.js +943 -0
  315. package/dist/addon-vitest/vitest-plugin/global-setup.js +162 -0
  316. package/dist/addon-vitest/vitest-plugin/index.d.ts +56 -0
  317. package/dist/addon-vitest/vitest-plugin/index.js +463 -0
  318. package/dist/addon-vitest/vitest-plugin/setup-file-with-project-annotations.js +9 -0
  319. package/dist/addon-vitest/vitest-plugin/setup-file.browser.4.js +20 -0
  320. package/dist/addon-vitest/vitest-plugin/setup-file.js +50 -0
  321. package/dist/addon-vitest/vitest-plugin/test-utils.js +128 -0
  322. package/dist/babel/index.d.ts +2301 -0
  323. package/dist/babel/index.js +61 -0
  324. package/dist/backgrounds/index.d.ts +6 -0
  325. package/dist/backgrounds/index.js +15 -0
  326. package/dist/bin/core.js +1705 -0
  327. package/dist/bin/dispatcher.js +43 -0
  328. package/dist/bin/loader.js +115 -0
  329. package/dist/builder-vite/index.d.ts +50 -0
  330. package/dist/builder-vite/index.js +245 -0
  331. package/dist/builder-vite/preset.js +27 -0
  332. package/dist/channels/index.d.ts +2 -0
  333. package/dist/channels/index.js +352 -0
  334. package/dist/chunk-B2t1tGRh.d.ts +284 -0
  335. package/dist/chunk-BCoJQE-f.d.ts +602 -0
  336. package/dist/chunk-BGkgZp-H.d.ts +214 -0
  337. package/dist/chunk-BTVrWliM.d.ts +115 -0
  338. package/dist/chunk-BXLImeLy.d.ts +197 -0
  339. package/dist/chunk-BfBzpgct.d.ts +916 -0
  340. package/dist/chunk-Bpi2tz-6.d.ts +511 -0
  341. package/dist/chunk-BxWufQms.d.ts +142 -0
  342. package/dist/chunk-C-bavsOH.d.ts +34 -0
  343. package/dist/chunk-C2p5r3Vt.d.ts +13001 -0
  344. package/dist/chunk-C6PAgHLT.d.ts +12 -0
  345. package/dist/chunk-CMeX4WRe.d.ts +179 -0
  346. package/dist/chunk-Ct9xd6IM.d.ts +65 -0
  347. package/dist/chunk-CwQKNaYL.d.ts +15 -0
  348. package/dist/chunk-D7DwV41f.d.ts +3622 -0
  349. package/dist/chunk-DEVFdzxR.d.ts +253 -0
  350. package/dist/chunk-DaVb55-_.d.ts +124 -0
  351. package/dist/chunk-DgRNfmj_.d.ts +40 -0
  352. package/dist/chunk-DoIGKY33.d.ts +666 -0
  353. package/dist/chunk-Dr3R0DXk.d.ts +40 -0
  354. package/dist/chunk-DtHByo32.d.ts +55 -0
  355. package/dist/chunk-Dw1z1Pki.d.ts +933 -0
  356. package/dist/chunk-DzuY9DXg.d.ts +79 -0
  357. package/dist/chunk-FjDVzZTj.d.ts +62 -0
  358. package/dist/chunk-Kt1tW-D1.d.ts +59 -0
  359. package/dist/chunk-XP8oHzpE.d.ts +6 -0
  360. package/dist/chunk-gCX81nOr.d.ts +61 -0
  361. package/dist/chunk-pcFXCimE.d.ts +741 -0
  362. package/dist/cli/index.d.ts +1174 -0
  363. package/dist/cli/index.js +5613 -0
  364. package/dist/cli/skills/content/index.d.ts +72 -0
  365. package/dist/cli/skills/content/index.js +335 -0
  366. package/dist/cli/tools/sdk/child-host.d.ts +61 -0
  367. package/dist/cli/tools/sdk/child-host.js +131 -0
  368. package/dist/cli/tools/sdk/index.d.ts +137 -0
  369. package/dist/cli/tools/sdk/index.js +44 -0
  370. package/dist/cli-commands/bin/index.js +25 -0
  371. package/dist/client-logger/index.d.ts +31 -0
  372. package/dist/client-logger/index.js +63 -0
  373. package/dist/common/index.d.ts +1103 -0
  374. package/dist/common/index.js +364 -0
  375. package/dist/components/index.d.ts +1924 -0
  376. package/dist/components/index.js +13759 -0
  377. package/dist/core-events/index.d.ts +155 -0
  378. package/dist/core-events/index.js +136 -0
  379. package/dist/core-server/index.d.ts +2200 -0
  380. package/dist/core-server/index.js +4165 -0
  381. package/dist/core-server/presets/common-manager.css +170 -0
  382. package/dist/core-server/presets/common-manager.js +4168 -0
  383. package/dist/core-server/presets/common-override-preset.js +81 -0
  384. package/dist/core-server/presets/common-preset.js +2187 -0
  385. package/dist/create/bin/index.js +23 -0
  386. package/dist/create/index.js +25 -0
  387. package/dist/csf/csf-utils.d.ts +2 -0
  388. package/dist/csf/csf-utils.js +19 -0
  389. package/dist/csf/index.d.ts +7 -0
  390. package/dist/csf/index.js +2142 -0
  391. package/dist/csf-tools/index.d.ts +1157 -0
  392. package/dist/csf-tools/index.js +736 -0
  393. package/dist/docs-tools/index.d.ts +197 -0
  394. package/dist/docs-tools/index.js +61 -0
  395. package/dist/highlight/index.d.ts +10 -0
  396. package/dist/highlight/index.js +15 -0
  397. package/dist/instrumenter/index.d.ts +113 -0
  398. package/dist/instrumenter/index.js +2595 -0
  399. package/dist/manager/_manager-chunks/globals-runtime-8HkdnU2F.js +6144 -0
  400. package/dist/manager/_manager-chunks/globals-runtime-BIKBO23x.js +3389 -0
  401. package/dist/manager/_manager-chunks/globals-runtime-BdGkqNEt.js +45 -0
  402. package/dist/manager/_manager-chunks/globals-runtime-BmphMP6z.js +1190 -0
  403. package/dist/manager/_manager-chunks/globals-runtime-BvM-NY2g.js +13307 -0
  404. package/dist/manager/_manager-chunks/globals-runtime-C02fvgcd.js +9243 -0
  405. package/dist/manager/_manager-chunks/globals-runtime-DkAPXCvc.js +9766 -0
  406. package/dist/manager/_manager-chunks/globals-runtime-DpNYC-qi.js +5564 -0
  407. package/dist/manager/_manager-chunks/globals-runtime-DtcOnYHR.js +5357 -0
  408. package/dist/manager/_manager-chunks/globals-runtime-DwFqpqya.js +722 -0
  409. package/dist/manager/_manager-chunks/globals-runtime-FC201B7s.js +6837 -0
  410. package/dist/manager/_manager-chunks/globals-runtime-Rp_zjGnh.js +121 -0
  411. package/dist/manager/_manager-chunks/globals-runtime-ZHrQFa3-.js +10463 -0
  412. package/dist/manager/_manager-chunks/globals-runtime-eLPTIfX-.js +7759 -0
  413. package/dist/manager/_manager-chunks/globals-runtime-qKvCZHFY.js +4468 -0
  414. package/dist/manager/_manager-chunks/globals-runtime-sGpNlIJ1.js +5102 -0
  415. package/dist/manager/_manager-chunks/runtime-B1L9TH89.js +452 -0
  416. package/dist/manager/_manager-chunks/runtime-BK0zF7FN.js +22 -0
  417. package/dist/manager/_manager-chunks/runtime-BhkT2CXl.js +1408 -0
  418. package/dist/manager/_manager-chunks/runtime-Bly6WJLN.js +998 -0
  419. package/dist/manager/_manager-chunks/runtime-D0UOWx0U.js +979 -0
  420. package/dist/manager/_manager-chunks/runtime-D94Vq3oR.js +4014 -0
  421. package/dist/manager/_manager-chunks/runtime-DMig8mT7.js +77 -0
  422. package/dist/manager/_manager-chunks/runtime-EITvVbkG.js +46 -0
  423. package/dist/manager/_manager-chunks/runtime-cp5pazY2.js +8936 -0
  424. package/dist/manager/_manager-chunks/runtime-eDVAYF7N.js +6860 -0
  425. package/dist/manager/_manager-chunks/runtime-i-PDAHLR.js +2493 -0
  426. package/dist/manager/globals-runtime.js +2 -0
  427. package/dist/manager/globals.d.ts +23 -0
  428. package/dist/manager/globals.js +26 -0
  429. package/dist/manager/manager-stores.d.ts +2 -0
  430. package/dist/manager/manager-stores.js +19 -0
  431. package/dist/manager/runtime.js +2 -0
  432. package/dist/manager-api/index.d.ts +2 -0
  433. package/dist/manager-api/index.js +3257 -0
  434. package/dist/manager-errors.d.ts +89 -0
  435. package/dist/manager-errors.js +20 -0
  436. package/dist/mcp/index.d.ts +270 -0
  437. package/dist/mcp/index.js +305 -0
  438. package/dist/mocking-utils/index.d.ts +689 -0
  439. package/dist/mocking-utils/index.js +521 -0
  440. package/dist/mocking-utils/mocker-runtime.js +1254 -0
  441. package/dist/nextjs-vite/config/preview.js +3 -0
  442. package/dist/nextjs-vite/export-mocks/cache/index.d.ts +25 -0
  443. package/dist/nextjs-vite/export-mocks/cache/index.js +29 -0
  444. package/dist/nextjs-vite/export-mocks/headers/index.d.ts +37 -0
  445. package/dist/nextjs-vite/export-mocks/headers/index.js +54 -0
  446. package/dist/nextjs-vite/export-mocks/link/index.d.ts +9 -0
  447. package/dist/nextjs-vite/export-mocks/link/index.js +59 -0
  448. package/dist/nextjs-vite/export-mocks/navigation/index.d.ts +28 -0
  449. package/dist/nextjs-vite/export-mocks/navigation/index.js +58 -0
  450. package/dist/nextjs-vite/export-mocks/router/index.d.ts +34 -0
  451. package/dist/nextjs-vite/export-mocks/router/index.js +63 -0
  452. package/dist/nextjs-vite/index.d.ts +92 -0
  453. package/dist/nextjs-vite/index.js +58 -0
  454. package/dist/nextjs-vite/node/index.d.ts +6 -0
  455. package/dist/nextjs-vite/node/index.js +20 -0
  456. package/dist/nextjs-vite/preset.js +648 -0
  457. package/dist/nextjs-vite/preview.d.ts +20 -0
  458. package/dist/nextjs-vite/preview.js +11 -0
  459. package/dist/nextjs-vite/vite-plugin/index.d.ts +6 -0
  460. package/dist/nextjs-vite/vite-plugin/index.js +19 -0
  461. package/dist/nextjs-vite-plugin/index.d.ts +28 -0
  462. package/dist/nextjs-vite-plugin/index.js +923 -0
  463. package/dist/nextjs-vite-plugin/mocks/storybook.global.js +29 -0
  464. package/dist/nextjs-vite-plugin/plugins/next-image/alias/image-context.js +8 -0
  465. package/dist/nextjs-vite-plugin/plugins/next-image/alias/image-default-loader.js +23 -0
  466. package/dist/nextjs-vite-plugin/plugins/next-image/alias/next-image.js +28 -0
  467. package/dist/nextjs-vite-plugin/plugins/next-image/alias/next-legacy-image.js +17 -0
  468. package/dist/nextjs-vite-plugin/plugins/next-mocks/alias/cache/index.js +29 -0
  469. package/dist/nextjs-vite-plugin/plugins/next-mocks/alias/dynamic/index.js +40 -0
  470. package/dist/nextjs-vite-plugin/plugins/next-mocks/alias/headers/index.js +55 -0
  471. package/dist/nextjs-vite-plugin/plugins/next-mocks/alias/link/index.js +63 -0
  472. package/dist/nextjs-vite-plugin/plugins/next-mocks/alias/navigation/index.js +71 -0
  473. package/dist/nextjs-vite-plugin/plugins/next-mocks/alias/router/index.js +74 -0
  474. package/dist/nextjs-vite-plugin/plugins/next-mocks/alias/rsc/server-only.js +7 -0
  475. package/dist/nextjs-vite-plugin/plugins/next-mocks/alias/safe-stable-stringify/index.js +13 -0
  476. package/dist/nextjs-vite-plugin/plugins/next-mocks/compatibility/draft-mode.compat.js +7 -0
  477. package/dist/node-logger/index.d.ts +495 -0
  478. package/dist/node-logger/index.js +42 -0
  479. package/dist/oxc-parser/index.d.ts +99 -0
  480. package/dist/oxc-parser/index.js +275 -0
  481. package/dist/oxc-parser/worker.js +37 -0
  482. package/dist/preview/_chunks/runtime-BIzIdDbb.js +10263 -0
  483. package/dist/preview/_chunks/runtime-BTPtVY1p.js +1102 -0
  484. package/dist/preview/_chunks/runtime-BZSnICCg.js +8484 -0
  485. package/dist/preview/_chunks/runtime-BdGkqNEt.js +45 -0
  486. package/dist/preview/_chunks/runtime-BwSxqk3t.js +63 -0
  487. package/dist/preview/_chunks/runtime-CqHxptiK.js +6143 -0
  488. package/dist/preview/_chunks/runtime-CsV4HZPV.js +5064 -0
  489. package/dist/preview/_chunks/runtime-CxZK_Ln3.js +284 -0
  490. package/dist/preview/_chunks/runtime-DZToXfvO.js +9767 -0
  491. package/dist/preview/_chunks/runtime-DrTjJkPY.js +3872 -0
  492. package/dist/preview/_chunks/runtime-DuHdxMFA.js +387 -0
  493. package/dist/preview/_chunks/runtime-iXdo8CR8.js +3635 -0
  494. package/dist/preview/_chunks/runtime-q3wt0e_N.js +6838 -0
  495. package/dist/preview/globals.d.ts +16 -0
  496. package/dist/preview/globals.js +20 -0
  497. package/dist/preview/runtime.js +6 -0
  498. package/dist/preview-api/index.d.ts +4 -0
  499. package/dist/preview-api/index.js +147 -0
  500. package/dist/preview-errors.d.ts +186 -0
  501. package/dist/preview-errors.js +56 -0
  502. package/dist/react/docgen/docgen-worker.js +38 -0
  503. package/dist/react/entry-preview-argtypes.js +9 -0
  504. package/dist/react/entry-preview-docs.js +12 -0
  505. package/dist/react/entry-preview-rsc.js +11 -0
  506. package/dist/react/entry-preview.js +21 -0
  507. package/dist/react/index.d.ts +119 -0
  508. package/dist/react/index.js +26 -0
  509. package/dist/react/preset.js +301 -0
  510. package/dist/react/preview.d.ts +2 -0
  511. package/dist/react/preview.js +11 -0
  512. package/dist/react-native/bin/get-stories.js +34 -0
  513. package/dist/react-native/index.d.ts +160 -0
  514. package/dist/react-native/index.js +1547 -0
  515. package/dist/react-native/metro/node.d.ts +83 -0
  516. package/dist/react-native/metro/node.js +21 -0
  517. package/dist/react-native/metro/withStorybook.d.ts +2269 -0
  518. package/dist/react-native/metro/withStorybook.js +138 -0
  519. package/dist/react-native/preview.d.ts +6 -0
  520. package/dist/react-native/preview.js +20 -0
  521. package/dist/react-native/scripts/generate.d.ts +22 -0
  522. package/dist/react-native/scripts/generate.js +18 -0
  523. package/dist/react-native/stub.js +20 -0
  524. package/dist/react-native-theming/index.d.ts +175 -0
  525. package/dist/react-native-theming/index.js +2591 -0
  526. package/dist/react-native-ui/index.d.ts +130 -0
  527. package/dist/react-native-ui/index.js +1448 -0
  528. package/dist/react-native-ui-common/index.d.ts +230 -0
  529. package/dist/react-native-ui-common/index.js +514 -0
  530. package/dist/react-vite/index.d.ts +4 -0
  531. package/dist/react-vite/index.js +8 -0
  532. package/dist/react-vite/node/index.d.ts +6 -0
  533. package/dist/react-vite/node/index.js +20 -0
  534. package/dist/react-vite/preset.d.ts +6 -0
  535. package/dist/react-vite/preset.js +21 -0
  536. package/dist/router/index.d.ts +141 -0
  537. package/dist/router/index.js +1217 -0
  538. package/dist/server-errors.d.ts +2 -0
  539. package/dist/server-errors.js +149 -0
  540. package/dist/shared/open-service/index.d.ts +3 -0
  541. package/dist/shared/open-service/index.js +115 -0
  542. package/dist/shared/open-service/services/docgen/worker/docgen-worker.js +75 -0
  543. package/dist/shared/open-service/toolsets/docs/public.d.ts +1296 -0
  544. package/dist/shared/open-service/toolsets/docs/public.js +991 -0
  545. package/dist/telemetry/index.d.ts +314 -0
  546. package/dist/telemetry/index.js +103 -0
  547. package/dist/test/index.d.ts +158 -0
  548. package/dist/test/index.js +19421 -0
  549. package/dist/theming/create.d.ts +15 -0
  550. package/dist/theming/create.js +11 -0
  551. package/dist/theming/index.d.ts +54 -0
  552. package/dist/theming/index.js +511 -0
  553. package/dist/types/index.d.ts +2 -0
  554. package/dist/types/index.js +48 -0
  555. package/dist/viewport/index.d.ts +275 -0
  556. package/dist/viewport/index.js +21 -0
  557. package/package.json +1054 -4
  558. package/template/nextjs-vite/cli/.eslintrc.json +6 -0
  559. package/template/nextjs-vite/cli/js/Button.jsx +42 -0
  560. package/template/nextjs-vite/cli/js/Button.stories.js +49 -0
  561. package/template/nextjs-vite/cli/js/Configure.mdx +470 -0
  562. package/template/nextjs-vite/cli/js/Header.jsx +58 -0
  563. package/template/nextjs-vite/cli/js/Header.stories.js +30 -0
  564. package/template/nextjs-vite/cli/js/Page.jsx +68 -0
  565. package/template/nextjs-vite/cli/js/Page.stories.js +28 -0
  566. package/template/nextjs-vite/cli/ts/Button.stories.ts +54 -0
  567. package/template/nextjs-vite/cli/ts/Button.tsx +39 -0
  568. package/template/nextjs-vite/cli/ts/Configure.mdx +446 -0
  569. package/template/nextjs-vite/cli/ts/Header.stories.ts +34 -0
  570. package/template/nextjs-vite/cli/ts/Header.tsx +54 -0
  571. package/template/nextjs-vite/cli/ts/Page.stories.ts +33 -0
  572. package/template/nextjs-vite/cli/ts/Page.tsx +73 -0
  573. package/template/react/cli/.eslintrc.json +5 -0
  574. package/template/react/cli/js/Button.jsx +39 -0
  575. package/template/react/cli/js/Button.stories.js +49 -0
  576. package/template/react/cli/js/Header.jsx +56 -0
  577. package/template/react/cli/js/Header.stories.js +29 -0
  578. package/template/react/cli/js/Page.jsx +69 -0
  579. package/template/react/cli/js/Page.stories.js +28 -0
  580. package/template/react/cli/ts/Button.stories.ts +54 -0
  581. package/template/react/cli/ts/Button.tsx +37 -0
  582. package/template/react/cli/ts/Header.stories.ts +34 -0
  583. package/template/react/cli/ts/Header.tsx +56 -0
  584. package/template/react/cli/ts/Page.stories.ts +33 -0
  585. package/template/react/cli/ts/Page.tsx +73 -0
  586. package/template/react-vite/cli/.eslintrc.json +5 -0
  587. package/template/react-vite/cli/js/Button.jsx +39 -0
  588. package/template/react-vite/cli/js/Button.stories.js +49 -0
  589. package/template/react-vite/cli/js/Header.jsx +56 -0
  590. package/template/react-vite/cli/js/Header.stories.js +29 -0
  591. package/template/react-vite/cli/js/Page.jsx +69 -0
  592. package/template/react-vite/cli/js/Page.stories.js +28 -0
  593. package/template/react-vite/cli/ts/Button.stories.ts +54 -0
  594. package/template/react-vite/cli/ts/Button.tsx +37 -0
  595. package/template/react-vite/cli/ts/Header.stories.ts +34 -0
  596. package/template/react-vite/cli/ts/Header.tsx +56 -0
  597. package/template/react-vite/cli/ts/Page.stories.ts +33 -0
  598. package/template/react-vite/cli/ts/Page.tsx +73 -0
@@ -0,0 +1,2700 @@
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";
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);
8
+
9
+ // ------------------------------------------------------------
10
+ // end of CJS compatibility banner, injected by Forkbook's esbuild configuration
11
+ // ------------------------------------------------------------
12
+ import {
13
+ Tag
14
+ } from "./chunk-SVTBJ7Q3.js";
15
+ import {
16
+ jsTsSourceExtensions
17
+ } from "./chunk-TNJIXE37.js";
18
+
19
+ // src/common/utils/module-resolver.ts
20
+ import { ResolverFactory } from "oxc-resolver";
21
+ var defaultResolveConditionNames = ["storybook", "import", "module", "default"];
22
+ function createModuleResolver(options = {}) {
23
+ let factory = new ResolverFactory({
24
+ ...options,
25
+ conditionNames: options.conditionNames ?? defaultResolveConditionNames
26
+ }), unwrap = (result, specifier, from) => {
27
+ if (result.path)
28
+ return result.path;
29
+ throw new Error(result.error ?? `Cannot resolve module '${specifier}' from '${from}'`);
30
+ };
31
+ return {
32
+ resolveFileSync: (fromFile, specifier) => unwrap(factory.resolveFileSync(fromFile, specifier), specifier, fromFile),
33
+ resolveSync: (fromDirectory, specifier) => unwrap(factory.sync(fromDirectory, specifier), specifier, fromDirectory)
34
+ };
35
+ }
36
+
37
+ // src/csf-tools/story-shape/imports.ts
38
+ import { types as t } from "@aussieljk/forkbook/internal/babel";
39
+ var isTypeSpecifier = (s) => t.isImportSpecifier(s) && s.importKind === "type", importedName = (im) => t.isIdentifier(im) ? im.name : im.value;
40
+ function collectImportBindings(program) {
41
+ let localToImport = /* @__PURE__ */ new Map();
42
+ for (let stmt of program.get("body")) {
43
+ if (!stmt.isImportDeclaration())
44
+ continue;
45
+ let decl = stmt.node;
46
+ if (decl.importKind !== "type")
47
+ for (let s of decl.specifiers ?? []) {
48
+ if (!("local" in s) || !s.local || isTypeSpecifier(s))
49
+ continue;
50
+ let importId = decl.source.value;
51
+ t.isImportDefaultSpecifier(s) ? localToImport.set(s.local.name, { importId, importName: "default" }) : t.isImportNamespaceSpecifier(s) ? localToImport.set(s.local.name, { importId, importName: "*" }) : t.isImportSpecifier(s) && localToImport.set(s.local.name, { importId, importName: importedName(s.imported) });
52
+ }
53
+ }
54
+ return localToImport;
55
+ }
56
+
57
+ // src/csf-tools/story-shape/import-statements.ts
58
+ import { babelParse, babelPrint, types as t2 } from "@aussieljk/forkbook/internal/babel";
59
+ function resolveComponentImport(componentName, bindings) {
60
+ let dot = componentName.indexOf("."), base = dot === -1 ? componentName : componentName.slice(0, dot), member = dot === -1 ? void 0 : componentName.slice(dot + 1), binding = bindings.get(base);
61
+ if (!binding)
62
+ return { componentName, ...member ? { member } : {} };
63
+ let isNamespace = binding.importName === "*";
64
+ return {
65
+ componentName,
66
+ ...member ? { member } : {},
67
+ localImportName: base,
68
+ importId: binding.importId,
69
+ importName: isNamespace && member ? member : binding.importName,
70
+ ...isNamespace ? { namespace: base } : {}
71
+ };
72
+ }
73
+ function parseImportOverride(code) {
74
+ let declaration;
75
+ try {
76
+ declaration = babelParse(code).program.body.find(
77
+ (node) => t2.isImportDeclaration(node)
78
+ );
79
+ } catch {
80
+ return;
81
+ }
82
+ if (!declaration)
83
+ return;
84
+ let source = declaration.source.value, specifier = (declaration.specifiers ?? []).find((s) => !isTypeSpecifier(s));
85
+ return t2.isImportNamespaceSpecifier(specifier) ? { source, specifier: { kind: "namespace", local: specifier.local.name } } : t2.isImportDefaultSpecifier(specifier) ? { source, specifier: { kind: "default" } } : t2.isImportSpecifier(specifier) ? { source, specifier: { kind: "named", imported: importedName(specifier.imported) } } : { source };
86
+ }
87
+ function addUniqueBy(list, item, eq) {
88
+ list.find(eq) || list.push(item);
89
+ }
90
+ function addNamed(bucket, local, imported) {
91
+ addUniqueBy(
92
+ bucket.named,
93
+ t2.importSpecifier(t2.identifier(local), t2.identifier(imported)),
94
+ (n) => n.local.name === local && importedName(n.imported) === imported
95
+ );
96
+ }
97
+ function addSingle(list, name) {
98
+ addUniqueBy(list, t2.identifier(name), (n) => n.name === name);
99
+ }
100
+ function collectSpecifier(bucket, ref, source, override) {
101
+ let rewritten = source !== ref.importId;
102
+ if (override?.specifier) {
103
+ let { specifier } = override;
104
+ if (specifier.kind === "namespace") {
105
+ addSingle(bucket.namespaces, specifier.local);
106
+ return;
107
+ }
108
+ if (!ref.localImportName)
109
+ return;
110
+ specifier.kind === "default" ? addSingle(bucket.defaults, ref.localImportName) : addNamed(bucket, ref.localImportName, specifier.imported);
111
+ return;
112
+ }
113
+ if (ref.namespace) {
114
+ let member = rewritten ? ref.importName : void 0;
115
+ member && member !== "*" && !member.includes(".") ? addNamed(bucket, member, member) : addSingle(bucket.namespaces, ref.namespace);
116
+ return;
117
+ }
118
+ if (ref.localImportName) {
119
+ if (ref.importName === "default") {
120
+ rewritten ? addNamed(bucket, ref.localImportName, ref.localImportName) : addSingle(bucket.defaults, ref.localImportName);
121
+ return;
122
+ }
123
+ ref.importName && addNamed(bucket, ref.localImportName, ref.importName);
124
+ }
125
+ }
126
+ function printBucket({ source, defaults, namespaces, named }) {
127
+ let print = (specifiers) => babelPrint(t2.importDeclaration(specifiers, source)), extraDefaults = defaults.slice(1).map((d) => print([t2.importDefaultSpecifier(d)]));
128
+ if (namespaces.length > 0) {
129
+ let first2 = [];
130
+ return defaults[0] && first2.push(t2.importDefaultSpecifier(defaults[0])), first2.push(t2.importNamespaceSpecifier(namespaces[0])), [
131
+ print(first2),
132
+ ...named.length > 0 ? [print(named)] : [],
133
+ ...extraDefaults,
134
+ ...namespaces.slice(1).map((ns) => print([t2.importNamespaceSpecifier(ns)]))
135
+ ];
136
+ }
137
+ if (defaults.length === 0 && named.length === 0)
138
+ return [];
139
+ let first = [];
140
+ return defaults[0] && first.push(t2.importDefaultSpecifier(defaults[0])), first.push(...named), [print(first), ...extraDefaults];
141
+ }
142
+ function buildImportStatements({
143
+ refs,
144
+ packageName
145
+ }) {
146
+ let buckets = /* @__PURE__ */ new Map();
147
+ return refs.forEach((ref) => {
148
+ if (!ref.importId)
149
+ return;
150
+ let override = ref.importOverride ? parseImportOverride(ref.importOverride) : void 0, source = override?.source ?? (packageName && !ref.isPackage ? packageName : ref.importId), bucket = buckets.get(source);
151
+ bucket || (bucket = { source: t2.stringLiteral(source), defaults: [], namespaces: [], named: [] }, buckets.set(source, bucket)), collectSpecifier(bucket, ref, source, override);
152
+ }), Array.from(buckets.values()).flatMap(printBucket);
153
+ }
154
+
155
+ // src/csf-tools/story-shape/utils.ts
156
+ import { types as t3 } from "@aussieljk/forkbook/internal/babel";
157
+ var unwrapExpression = (node) => t3.isTSAsExpression(node) || t3.isTSSatisfiesExpression(node) || t3.isTSNonNullExpression(node) || t3.isTSTypeAssertion(node) || t3.isParenthesizedExpression(node) ? unwrapExpression(node.expression) : node, isCanonicalCsf2BindCall = (node) => t3.isCallExpression(node) && t3.isMemberExpression(node.callee) && !node.callee.computed && t3.isIdentifier(node.callee.object) && t3.isIdentifier(node.callee.property, { name: "bind" }) && (node.arguments.length === 0 || node.arguments.length === 1 && t3.isObjectExpression(node.arguments[0]) && node.arguments[0].properties.length === 0), withoutTypeCalls = (object) => t3.isCallExpression(object) && object.arguments.length === 0 && t3.isMemberExpression(object.callee) && !object.callee.computed && t3.isIdentifier(object.callee.property, { name: "type" }) ? withoutTypeCalls(object.callee.object) : object, isCsfFactoryCall = (node) => t3.isCallExpression(node) && t3.isMemberExpression(node.callee) && !node.callee.computed && t3.isIdentifier(withoutTypeCalls(node.callee.object)) && t3.isIdentifier(node.callee.property) && (node.callee.property.name === "story" || node.callee.property.name === "extend"), csfFactoryReceiver = (node) => withoutTypeCalls(node.callee.object), templateParts = (node) => {
158
+ if (t3.isTemplateLiteral(node))
159
+ return {
160
+ quasis: node.quasis.map((quasi) => quasi.value.cooked ?? ""),
161
+ expressions: node.expressions
162
+ };
163
+ if (!(!t3.isTaggedTemplateExpression(node) || !isStringRawTag(node.tag)))
164
+ return {
165
+ quasis: node.quasi.quasis.map((quasi) => quasi.value.raw),
166
+ expressions: node.quasi.expressions
167
+ };
168
+ }, isStringRawTag = (tag) => t3.isMemberExpression(tag) && !tag.computed && t3.isIdentifier(tag.object, { name: "String" }) && t3.isIdentifier(tag.property, { name: "raw" }), keyOf = (p) => t3.isStringLiteral(p.key) ? p.key.value : !p.computed && t3.isIdentifier(p.key) ? p.key.name : null, propertyValue = (object, name) => object?.properties.find(
169
+ (candidate) => t3.isObjectProperty(candidate) && keyOf(candidate) === name
170
+ )?.value, soleReturnedExpression = (body) => {
171
+ let [statement, ...rest] = body.body;
172
+ return rest.length === 0 && t3.isReturnStatement(statement) && t3.isExpression(statement.argument) ? statement.argument : void 0;
173
+ }, returnedExpression = (fn) => {
174
+ if (t3.isFunction(fn))
175
+ return t3.isExpression(fn.body) ? fn.body : soleReturnedExpression(fn.body);
176
+ }, returnedExpressionPath = (renderFunction) => {
177
+ if (!returnedExpression(renderFunction.node))
178
+ return;
179
+ let body = renderFunction.get("body");
180
+ if (body.isExpression())
181
+ return body;
182
+ let [statement] = body.isBlockStatement() ? body.get("body") : [], argument = statement?.isReturnStatement() ? statement.get("argument") : void 0;
183
+ return argument?.isExpression() ? argument : void 0;
184
+ }, resolveReturnedObjectExpression = (renderFunction) => {
185
+ let returned = returnedExpressionPath(renderFunction);
186
+ if (returned?.isObjectExpression())
187
+ return returned.node;
188
+ if (!returned?.isIdentifier())
189
+ return;
190
+ let resolved = resolveIdentifierInit(renderFunction, returned);
191
+ return resolved?.isObjectExpression() ? resolved.node : void 0;
192
+ };
193
+ function resolveIdentifierInit(storyPath, identifier) {
194
+ let programPath = storyPath.findParent((p) => p.isProgram());
195
+ if (!programPath)
196
+ return null;
197
+ for (let stmt of programPath.get("body")) {
198
+ if (stmt.isFunctionDeclaration() && stmt.node.id?.name === identifier.node.name)
199
+ return stmt;
200
+ if (stmt.isExportNamedDeclaration()) {
201
+ let decl = stmt.get("declaration");
202
+ if (decl.isFunctionDeclaration() && decl.node.id?.name === identifier.node.name)
203
+ return decl;
204
+ }
205
+ }
206
+ let match = programPath.get("body").flatMap((stmt) => {
207
+ if (stmt.isVariableDeclaration())
208
+ return stmt.get("declarations");
209
+ if (stmt.isExportNamedDeclaration()) {
210
+ let decl = stmt.get("declaration");
211
+ if (decl && decl.isVariableDeclaration())
212
+ return decl.get("declarations");
213
+ }
214
+ return [];
215
+ }).find((d) => {
216
+ let id = d.get("id");
217
+ return id.isIdentifier() && id.node.name === identifier.node.name;
218
+ });
219
+ if (!match)
220
+ return null;
221
+ let init = match.get("init");
222
+ return init && init.isExpression() ? init : null;
223
+ }
224
+ function pathForNode(program, target) {
225
+ if (!target)
226
+ return;
227
+ let found;
228
+ return program.traverse({
229
+ enter(p) {
230
+ p.node && p.node === target && (found = p, p.stop());
231
+ }
232
+ }), found;
233
+ }
234
+ function metaObjectPath(csf) {
235
+ let metaPath = pathForNode(csf._file.path, csf._metaNode);
236
+ return metaPath?.isObjectExpression() ? metaPath : void 0;
237
+ }
238
+
239
+ // src/csf-tools/story-shape/resolve-members.ts
240
+ import { generate, types as t4 } from "@aussieljk/forkbook/internal/babel";
241
+ var sourceOf = (node) => generate(node, { concise: !0, comments: !1 }).code, complete = (properties = {}) => ({
242
+ properties,
243
+ shadowed: [],
244
+ unresolved: []
245
+ }), resolveObjectMembers = (object, ctx) => membersOf(object, ctx, /* @__PURE__ */ new Set()), resolveArgsRecord = (node, ctx) => {
246
+ if (node === void 0)
247
+ return complete();
248
+ let unwrapped = unwrapExpression(node);
249
+ if (t4.isObjectExpression(unwrapped))
250
+ return asArgsRecord(membersOf(unwrapped, ctx, /* @__PURE__ */ new Set()));
251
+ let referenced = resolveReference(ctx, unwrapped, node.start ?? void 0, /* @__PURE__ */ new Set());
252
+ return referenced ? asArgsRecord(referenced) : { properties: {}, shadowed: [], unresolved: [`args: ${sourceOf(unwrapped)}`] };
253
+ }, asArgsRecord = (members) => {
254
+ let methods = Object.entries(members.properties).filter(([, node]) => t4.isObjectMethod(node));
255
+ if (methods.length === 0)
256
+ return members;
257
+ let properties = { ...members.properties }, unresolved = [...members.unresolved];
258
+ for (let [key, node] of methods)
259
+ delete properties[key], unresolved.push(sourceOf(node));
260
+ return {
261
+ properties,
262
+ shadowed: members.shadowed.filter((key) => key in properties),
263
+ unresolved
264
+ };
265
+ }, resolveBindingMembers = (ctx, name) => {
266
+ let bound = bindingMembers(ctx, name, void 0, /* @__PURE__ */ new Set());
267
+ return bound === void 0 || bound.kind === "namespace" ? void 0 : bound.members;
268
+ }, resolveReferencedValue = (ctx, expression) => {
269
+ let chain = memberChain(expression);
270
+ if (!chain || chain.path.length === 0)
271
+ return;
272
+ let visited = /* @__PURE__ */ new Set(), located = locate(ctx, chain, void 0, visited);
273
+ if (!located || located.path.length === 0)
274
+ return;
275
+ let members = located.members, scope = located.ctx;
276
+ for (let [index, key] of located.path.entries()) {
277
+ if (members.shadowed.includes(key))
278
+ return;
279
+ let value = members.properties[key];
280
+ if (value === void 0)
281
+ return;
282
+ if (index === located.path.length - 1)
283
+ return { node: value, ctx: scope };
284
+ let unwrapped = unwrapExpression(value);
285
+ if (!t4.isObjectExpression(unwrapped))
286
+ return;
287
+ members = membersOf(unwrapped, scope, visited);
288
+ }
289
+ }, membersOf = (object, ctx, visited) => {
290
+ let properties = {}, unresolved = [], shadowed = /* @__PURE__ */ new Set(), shadowKnownMembers = (source) => {
291
+ unresolved.push(source);
292
+ for (let key of Object.keys(properties))
293
+ shadowed.add(key);
294
+ };
295
+ for (let property of object.properties) {
296
+ if (t4.isSpreadElement(property)) {
297
+ let spread = spreadMembers(ctx, property, visited);
298
+ if (spread === void 0 || spread.unresolved.length > 0) {
299
+ shadowKnownMembers(sourceOf(property));
300
+ continue;
301
+ }
302
+ for (let [key2, value] of Object.entries(spread.properties))
303
+ properties[key2] = value, shadowed.delete(key2);
304
+ continue;
305
+ }
306
+ let key = keyOf(property);
307
+ if (key === null) {
308
+ shadowKnownMembers(sourceOf(property));
309
+ continue;
310
+ }
311
+ if (t4.isObjectMethod(property) && (property.kind !== "method" || property.generator)) {
312
+ delete properties[key], shadowed.delete(key), unresolved.push(sourceOf(property));
313
+ continue;
314
+ }
315
+ properties[key] = t4.isObjectMethod(property) ? property : property.value, shadowed.delete(key);
316
+ }
317
+ return { properties, shadowed: [...shadowed], unresolved };
318
+ }, spreadMembers = (ctx, spread, visited) => {
319
+ let argument = unwrapExpression(spread.argument);
320
+ return t4.isObjectExpression(argument) ? membersOf(argument, ctx, visited) : resolveReference(ctx, argument, spread.start ?? void 0, visited);
321
+ }, memberChain = (node) => {
322
+ let path = [], current = unwrapExpression(node);
323
+ for (; t4.isMemberExpression(current); ) {
324
+ let key = t4.isIdentifier(current.property) && !current.computed ? current.property.name : t4.isStringLiteral(current.property) ? current.property.value : void 0;
325
+ if (key === void 0)
326
+ return;
327
+ path.unshift(key), current = unwrapExpression(current.object);
328
+ }
329
+ return t4.isIdentifier(current) ? { root: current.name, path } : void 0;
330
+ }, resolveReference = (ctx, expression, position, visited) => {
331
+ let chain = memberChain(expression);
332
+ if (!chain)
333
+ return;
334
+ let key = `ref:${ctx.filePath}#${chain.root}.${chain.path.join(".")}`;
335
+ if (!visited.has(key)) {
336
+ visited.add(key);
337
+ try {
338
+ return unguardedResolveReference(ctx, chain, position, visited);
339
+ } finally {
340
+ visited.delete(key);
341
+ }
342
+ }
343
+ }, unguardedResolveReference = (ctx, chain, position, visited) => {
344
+ let located = locate(ctx, chain, position, visited);
345
+ if (!located)
346
+ return;
347
+ let members = located.members, scope = located.ctx;
348
+ for (let [index, key] of located.path.entries()) {
349
+ if (members.unresolved.length > 0)
350
+ return;
351
+ let value = members.properties[key];
352
+ if (value === void 0)
353
+ return index === located.path.length - 1 ? complete() : void 0;
354
+ let unwrapped = unwrapExpression(value);
355
+ if (!t4.isObjectExpression(unwrapped))
356
+ return;
357
+ members = membersOf(unwrapped, scope, visited);
358
+ }
359
+ return located.external ? externalized(members, scope) : members;
360
+ }, locate = (ctx, chain, position, visited) => {
361
+ let binding = bindingMembers(ctx, chain.root, position, visited);
362
+ if (!binding)
363
+ return;
364
+ if (binding.kind === "namespace") {
365
+ let [exportName, ...path] = chain.path;
366
+ if (exportName === void 0)
367
+ return;
368
+ let exported = bindingMembers(binding.ctx, exportName, void 0, visited);
369
+ if (exported === void 0 || exported.kind === "namespace")
370
+ return;
371
+ let located2 = withAccessor(exported, path);
372
+ return located2 === void 0 ? void 0 : { ...located2, external: !0 };
373
+ }
374
+ let located = withAccessor(binding, chain.path);
375
+ return located === void 0 ? void 0 : { ...located, external: binding.external };
376
+ }, withAccessor = (binding, path) => binding.accessor === void 0 ? { members: binding.members, ctx: binding.ctx, path } : path[0] === binding.accessor ? { members: binding.members, ctx: binding.ctx, path: path.slice(1) } : void 0, externalized = (members, ctx) => {
377
+ if (!ctx.externalize)
378
+ return members;
379
+ let properties = {};
380
+ for (let [key, node] of Object.entries(members.properties)) {
381
+ let value = ctx.externalize(node);
382
+ if (value === void 0)
383
+ return;
384
+ properties[key] = value;
385
+ }
386
+ return {
387
+ properties,
388
+ shadowed: members.shadowed,
389
+ unresolved: members.unresolved
390
+ };
391
+ }, bindingMembers = (ctx, name, position, visited) => {
392
+ let key = `${ctx.filePath}#${name}`;
393
+ if (!visited.has(key)) {
394
+ visited.add(key);
395
+ try {
396
+ return unguardedBindingMembers(ctx, name, position, visited);
397
+ } finally {
398
+ visited.delete(key);
399
+ }
400
+ }
401
+ }, unguardedBindingMembers = (ctx, name, position, visited) => {
402
+ let binding = ctx.program.scope.getBinding(name);
403
+ if (!binding)
404
+ return;
405
+ if (binding.kind === "module")
406
+ return importedBinding(ctx, binding.path, visited);
407
+ if (!binding.constant)
408
+ return;
409
+ let rootName = localAliasRoot(ctx, name), rootBinding = ctx.program.scope.getBinding(rootName), declared = declaredBindingMembers(
410
+ ctx,
411
+ rootBinding?.path.node ?? binding.path.node,
412
+ position,
413
+ visited
414
+ );
415
+ if (declared === void 0)
416
+ return;
417
+ let assigned = assignedMembers(ctx, localAliases(ctx, rootName), position);
418
+ return {
419
+ kind: "members",
420
+ ctx,
421
+ external: !1,
422
+ ...declared.accessor ? { accessor: declared.accessor } : {},
423
+ members: {
424
+ properties: { ...declared.members.properties, ...assigned.properties },
425
+ shadowed: declared.members.shadowed.filter((key) => !(key in assigned.properties)),
426
+ unresolved: [...declared.members.unresolved, ...assigned.unresolved]
427
+ }
428
+ };
429
+ }, declaredBindingMembers = (ctx, node, position, visited) => {
430
+ if (t4.isFunctionDeclaration(node))
431
+ return { members: complete() };
432
+ if (t4.isVariableDeclarator(node) && !(position !== void 0 && (node.start ?? Number.POSITIVE_INFINITY) > position))
433
+ return node.init ? declaredMembers(ctx, node.init, position, visited) : { members: complete() };
434
+ }, declaredMembers = (ctx, init, position, visited) => {
435
+ let unwrapped = unwrapExpression(init);
436
+ if (t4.isObjectExpression(unwrapped))
437
+ return { members: membersOf(unwrapped, ctx, visited) };
438
+ let factory = factoryCall(unwrapped);
439
+ if (factory === void 0 && (t4.isFunction(unwrapped) || isCanonicalCsf2BindCall(unwrapped)))
440
+ return { members: complete() };
441
+ if (t4.isIdentifier(unwrapped)) {
442
+ let referenced = bindingMembers(ctx, unwrapped.name, position, visited);
443
+ if (referenced?.kind === "members") {
444
+ let members = referenced.external ? ctx.externalize && externalized(referenced.members, referenced.ctx) : referenced.members;
445
+ if (members)
446
+ return { members, ...referenced.accessor ? { accessor: referenced.accessor } : {} };
447
+ }
448
+ }
449
+ if (factory === void 0)
450
+ return {
451
+ members: { properties: {}, shadowed: [], unresolved: [sourceOf(unwrapped)] }
452
+ };
453
+ let config = factory.config ? membersOf(factory.config, ctx, visited) : complete();
454
+ if (factory.method === "story")
455
+ return { members: config, accessor: "input" };
456
+ let parent = bindingMembers(ctx, factory.parent, position, visited);
457
+ return parent === void 0 || parent.kind === "namespace" || parent.accessor !== "input" || parent.external ? void 0 : {
458
+ members: {
459
+ properties: mergedAnnotations(parent.members, config).properties,
460
+ shadowed: [
461
+ ...parent.members.shadowed.filter((key) => !(key in config.properties)),
462
+ ...config.shadowed
463
+ ],
464
+ unresolved: [...parent.members.unresolved, ...config.unresolved]
465
+ },
466
+ accessor: "input"
467
+ };
468
+ }, MERGED_ANNOTATIONS = ["args", "argTypes", "parameters", "globals"], localAliasRoot = (ctx, name) => {
469
+ let visited = /* @__PURE__ */ new Set(), current = name;
470
+ for (; !visited.has(current); ) {
471
+ visited.add(current);
472
+ let binding = ctx.program.scope.getBinding(current), node = binding?.path.node;
473
+ if (!binding?.constant || !t4.isVariableDeclarator(node) || !node.init)
474
+ break;
475
+ let init = unwrapExpression(node.init);
476
+ if (!t4.isIdentifier(init))
477
+ break;
478
+ let target = ctx.program.scope.getBinding(init.name);
479
+ if (!target?.constant || target.kind === "module")
480
+ break;
481
+ current = init.name;
482
+ }
483
+ return current;
484
+ }, localAliases = (ctx, root) => {
485
+ let aliases = /* @__PURE__ */ new Map([[root, Number.NEGATIVE_INFINITY]]);
486
+ for (let [name, binding] of Object.entries(ctx.program.scope.bindings))
487
+ name !== root && binding.constant && localAliasRoot(ctx, name) === root && aliases.set(name, binding.path.node.start ?? Number.POSITIVE_INFINITY);
488
+ return aliases;
489
+ }, mergedAnnotations = (parent, child) => {
490
+ let properties = { ...parent.properties, ...child.properties };
491
+ for (let key of MERGED_ANNOTATIONS) {
492
+ let from = parent.properties[key], over = child.properties[key];
493
+ from === void 0 || over === void 0 || !t4.isExpression(from) || !t4.isExpression(over) || (properties[key] = t4.objectExpression([t4.spreadElement(from), t4.spreadElement(over)]));
494
+ }
495
+ return { properties };
496
+ }, factoryCall = (node) => {
497
+ if (!isCsfFactoryCall(node))
498
+ return;
499
+ let method = node.callee.property.name;
500
+ if (method !== "story" && method !== "extend")
501
+ return;
502
+ let [argument] = node.arguments, config = argument && unwrapExpression(argument);
503
+ if (!(argument !== void 0 && (config === void 0 || !t4.isObjectExpression(config))))
504
+ return {
505
+ method,
506
+ parent: csfFactoryReceiver(node).name,
507
+ ...config && t4.isObjectExpression(config) ? { config } : {}
508
+ };
509
+ }, assignedMembers = (ctx, aliases, position) => {
510
+ let properties = {}, unresolved = [];
511
+ for (let statement of ctx.program.node.body) {
512
+ if (!t4.isExpressionStatement(statement) || !t4.isAssignmentExpression(statement.expression))
513
+ continue;
514
+ let assignment = statement.expression, target = assignment.left, depth = 0, outermost;
515
+ for (; t4.isMemberExpression(target); )
516
+ depth += 1, outermost = t4.isIdentifier(target.property) && !target.computed ? target.property.name : t4.isStringLiteral(target.property) ? target.property.value : void 0, target = target.object;
517
+ if (!(depth === 0 || !t4.isIdentifier(target) || !aliases.has(target.name)) && !((assignment.start ?? 0) < aliases.get(target.name)) && !(position !== void 0 && (assignment.start ?? 0) > position)) {
518
+ if (depth > 1 || outermost === void 0 || assignment.operator !== "=") {
519
+ unresolved.push(sourceOf(assignment));
520
+ continue;
521
+ }
522
+ properties[outermost] = assignment.right;
523
+ }
524
+ }
525
+ return { properties, unresolved };
526
+ }, importedBinding = (ctx, specifierPath, visited) => {
527
+ let specifier = specifierPath.node, declaration = specifierPath.parent;
528
+ if (!t4.isImportDeclaration(declaration) || declaration.importKind === "type" || !(t4.isImportSpecifier(specifier) || t4.isImportDefaultSpecifier(specifier) || t4.isImportNamespaceSpecifier(specifier)) || isTypeSpecifier(specifier))
529
+ return;
530
+ let target = resolveTargetModule(ctx, declaration.source.value);
531
+ if (!target)
532
+ return;
533
+ if (t4.isImportNamespaceSpecifier(specifier))
534
+ return { kind: "namespace", ctx: target };
535
+ let exportName = t4.isImportDefaultSpecifier(specifier) ? "default" : importedName(specifier.imported);
536
+ return exportedBinding(target, exportName, visited);
537
+ }, resolveTargetModule = (ctx, specifier) => {
538
+ let target = ctx.resolveModule?.(ctx.filePath, specifier);
539
+ return target ? { ...ctx, ...target } : void 0;
540
+ }, exportedBinding = (ctx, exportName, visited) => {
541
+ let asExternal = (bound) => bound === void 0 || bound.kind === "namespace" ? bound : { ...bound, external: !0 };
542
+ for (let statement of ctx.program.node.body) {
543
+ if (t4.isExportDefaultDeclaration(statement) && exportName === "default") {
544
+ let declaration = unwrapExpression(statement.declaration);
545
+ return t4.isIdentifier(declaration) ? asExternal(bindingMembers(ctx, declaration.name, void 0, visited)) : t4.isObjectExpression(declaration) ? {
546
+ kind: "members",
547
+ ctx,
548
+ external: !0,
549
+ members: membersOf(declaration, ctx, visited)
550
+ } : void 0;
551
+ }
552
+ if (!t4.isExportNamedDeclaration(statement) || statement.exportKind === "type")
553
+ continue;
554
+ let specifier = statement.specifiers.find(
555
+ (candidate) => t4.isExportSpecifier(candidate) && candidate.exportKind !== "type" && importedName(candidate.exported) === exportName
556
+ );
557
+ if (!specifier)
558
+ continue;
559
+ if (!statement.source)
560
+ return asExternal(bindingMembers(ctx, specifier.local.name, void 0, visited));
561
+ let target = resolveTargetModule(ctx, statement.source.value);
562
+ return target ? exportedBinding(target, specifier.local.name, visited) : void 0;
563
+ }
564
+ return exportName === "default" ? void 0 : asExternal(bindingMembers(ctx, exportName, void 0, visited));
565
+ };
566
+
567
+ // src/csf-tools/story-shape/resolve-arg-value.ts
568
+ import { traverse, types as t5 } from "@aussieljk/forkbook/internal/babel";
569
+ var resolveArgValue = (node, ctx) => {
570
+ let unresolved = [], resolved = inlineSpreads(
571
+ followValue(unwrapExpression(node), ctx, /* @__PURE__ */ new Set()),
572
+ ctx,
573
+ unresolved
574
+ ), bindings = importBindingsOf(ctx.program), imports = [];
575
+ for (let name of freeNames(resolved)) {
576
+ let imported = bindings.get(name);
577
+ if (imported) {
578
+ imports.push({
579
+ localImportName: name,
580
+ importId: imported.importId,
581
+ importName: imported.importName,
582
+ ...imported.importName === "*" ? { namespace: name } : {}
583
+ });
584
+ continue;
585
+ }
586
+ ctx.program.scope.getBinding(name) && unresolved.push(name);
587
+ }
588
+ return { node: resolved, imports, unresolved };
589
+ }, isSelfContained = (node) => freeNames(node).size === 0, importBindings = /* @__PURE__ */ new WeakMap(), importBindingsOf = (program) => {
590
+ let bindings = importBindings.get(program.node);
591
+ return bindings === void 0 && (bindings = collectImportBindings(program), importBindings.set(program.node, bindings)), bindings;
592
+ }, inlineSpreads = (node, ctx, unresolved) => {
593
+ if (!hasNamedSpread(node))
594
+ return node;
595
+ if (t5.isArrayExpression(node))
596
+ return t5.arrayExpression(
597
+ node.elements.map(
598
+ (element) => element && t5.isExpression(element) ? inlineSpreads(element, ctx, unresolved) : element
599
+ )
600
+ );
601
+ if (!t5.isObjectExpression(node))
602
+ return node;
603
+ if (!node.properties.some((property) => t5.isSpreadElement(property)))
604
+ return objectFrom(node.properties, ctx, unresolved) ?? node;
605
+ let members = resolveArgsRecord(node, ctx);
606
+ return members.unresolved.length > 0 ? (unresolved.push(...members.unresolved), node) : objectFrom(
607
+ Object.entries(members.properties).map(
608
+ ([key, value]) => t5.objectProperty(
609
+ t5.isValidIdentifier(key) ? t5.identifier(key) : t5.stringLiteral(key),
610
+ value
611
+ )
612
+ ),
613
+ ctx,
614
+ unresolved
615
+ ) ?? node;
616
+ }, hasNamedSpread = (node) => t5.isArrayExpression(node) ? node.elements.some(
617
+ (element) => element !== null && t5.isExpression(element) && hasNamedSpread(element)
618
+ ) : t5.isObjectExpression(node) && node.properties.some(
619
+ (property) => t5.isSpreadElement(property) ? !t5.isObjectExpression(unwrapExpression(property.argument)) : t5.isObjectProperty(property) && t5.isExpression(property.value) && hasNamedSpread(property.value)
620
+ ), objectFrom = (properties, ctx, unresolved) => {
621
+ let rebuilt = [];
622
+ for (let property of properties) {
623
+ if (!t5.isObjectProperty(property) || !t5.isExpression(property.value))
624
+ return;
625
+ let value = inlineSpreads(property.value, ctx, unresolved);
626
+ rebuilt.push(
627
+ t5.objectProperty(
628
+ property.key,
629
+ value,
630
+ property.computed,
631
+ property.shorthand && value === property.value
632
+ )
633
+ );
634
+ }
635
+ return t5.objectExpression(rebuilt);
636
+ }, followValue = (node, ctx, seen) => {
637
+ if (!t5.isIdentifier(node) || seen.has(node.name))
638
+ return node;
639
+ let binding = ctx.program.scope.getBinding(node.name);
640
+ return !binding || binding.kind === "module" || !binding.constant || !t5.isVariableDeclarator(binding.path.node) || !binding.path.node.init ? node : (seen.add(node.name), followValue(unwrapExpression(binding.path.node.init), ctx, seen));
641
+ }, freeNames = (node) => {
642
+ let expression = t5.isExpression(node) ? node : t5.isObjectMethod(node) ? t5.objectExpression([node]) : void 0;
643
+ if (expression === void 0)
644
+ throw new Error(`Cannot read the names a ${node.type} depends on: it is not an expression`);
645
+ let wrapped = t5.file(
646
+ t5.program([t5.expressionStatement(t5.cloneNode(expression, !0))])
647
+ ), names = /* @__PURE__ */ new Set();
648
+ return traverse(wrapped, {
649
+ ReferencedIdentifier(path) {
650
+ path.scope.hasBinding(path.node.name) || names.add(path.node.name);
651
+ }
652
+ }), names;
653
+ };
654
+
655
+ // src/csf-tools/story-shape/authored-source.ts
656
+ import { types as t6 } from "@aussieljk/forkbook/internal/babel";
657
+ var authoredSource = (shape, ctx) => {
658
+ for (let members of [shape.storyMembers, shape.metaMembers]) {
659
+ let code = memberAt(members, ["parameters", "docs", "source", "code"], ctx);
660
+ if (code.kind === "missing")
661
+ continue;
662
+ if (code.kind === "masked")
663
+ return { kind: "missing" };
664
+ if (code.kind === "unresolvable")
665
+ return code;
666
+ let resolved = resolveArgValue(code.node, ctx), value = unwrapExpression(resolved.node);
667
+ if (t6.isIdentifier(value, { name: "undefined" }) || t6.isUnaryExpression(value, { operator: "void" }))
668
+ continue;
669
+ if (t6.isNullLiteral(value))
670
+ return { kind: "disabled" };
671
+ if (t6.isStringLiteral(value))
672
+ return { kind: "code", code: value.value };
673
+ let parts = templateParts(value);
674
+ return parts && parts.expressions.length === 0 ? { kind: "code", code: parts.quasis[0] ?? "" } : { kind: "unresolvable", source: sourceOf(code.node) };
675
+ }
676
+ return { kind: "missing" };
677
+ }, memberAt = (members, path, ctx) => {
678
+ let result = memberOf(members, path[0]);
679
+ for (let [depth, key] of path.slice(1).entries()) {
680
+ if (result.kind !== "value")
681
+ return result;
682
+ let original = result.node, object = unwrapExpression(resolveArgValue(original, ctx).node);
683
+ if (!t6.isObjectExpression(object))
684
+ return t6.isIdentifier(object, { name: "undefined" }) || t6.isUnaryExpression(object, { operator: "void" }) ? { kind: "missing" } : isOpaqueValue(object) ? { kind: "unresolvable", source: sourceOf(original) } : depth === 0 ? { kind: "missing" } : { kind: "masked" };
685
+ result = memberOf(resolveObjectMembers(object, ctx), key);
686
+ }
687
+ return result;
688
+ }, memberOf = (members, key) => {
689
+ let node = members.properties[key];
690
+ return node !== void 0 && !members.shadowed.includes(key) ? { kind: "value", node } : members.unresolved.length > 0 ? { kind: "unresolvable", source: members.unresolved.at(-1) } : { kind: "missing" };
691
+ }, isOpaqueValue = (node) => !t6.isLiteral(node) && !t6.isArrayExpression(node) && !t6.isFunction(node);
692
+
693
+ // src/csf-tools/enrichCsf.ts
694
+ import { generate as generate2, types as t7 } from "@aussieljk/forkbook/internal/babel";
695
+ var enrichCsfStory = (csf, csfSource, key, options) => {
696
+ let storyExport = csfSource.getStoryExport(key), source = !options?.disableSource && extractSource(storyExport), description = !options?.disableDescription && extractDescription(csfSource._storyStatements[key]), parameters = [], baseStoryObject = csfSource._metaIsFactory ? t7.memberExpression(t7.identifier(key), t7.identifier("input")) : t7.identifier(key), originalParameters = t7.memberExpression(baseStoryObject, t7.identifier("parameters"));
697
+ parameters.push(t7.spreadElement(originalParameters));
698
+ let optionalDocs = t7.optionalMemberExpression(
699
+ originalParameters,
700
+ t7.identifier("docs"),
701
+ !1,
702
+ !0
703
+ ), extraDocsParameters = [];
704
+ if (source) {
705
+ let optionalSource = t7.optionalMemberExpression(
706
+ optionalDocs,
707
+ t7.identifier("source"),
708
+ !1,
709
+ !0
710
+ );
711
+ extraDocsParameters.push(
712
+ t7.objectProperty(
713
+ t7.identifier("source"),
714
+ t7.objectExpression([
715
+ t7.objectProperty(t7.identifier("originalSource"), t7.stringLiteral(source)),
716
+ t7.spreadElement(optionalSource)
717
+ ])
718
+ )
719
+ );
720
+ }
721
+ if (description) {
722
+ let optionalDescription = t7.optionalMemberExpression(
723
+ optionalDocs,
724
+ t7.identifier("description"),
725
+ !1,
726
+ !0
727
+ );
728
+ extraDocsParameters.push(
729
+ t7.objectProperty(
730
+ t7.identifier("description"),
731
+ t7.objectExpression([
732
+ t7.objectProperty(t7.identifier("story"), t7.stringLiteral(description)),
733
+ t7.spreadElement(optionalDescription)
734
+ ])
735
+ )
736
+ );
737
+ }
738
+ if (extraDocsParameters.length > 0) {
739
+ parameters.push(
740
+ t7.objectProperty(
741
+ t7.identifier("docs"),
742
+ t7.objectExpression([t7.spreadElement(optionalDocs), ...extraDocsParameters])
743
+ )
744
+ );
745
+ let addParameter = t7.expressionStatement(
746
+ t7.assignmentExpression("=", originalParameters, t7.objectExpression(parameters))
747
+ );
748
+ csf._ast.program.body.push(addParameter);
749
+ }
750
+ }, addComponentDescription = (node, path, value) => {
751
+ if (!path.length) {
752
+ node.properties.find(
753
+ (p) => t7.isObjectProperty(p) && t7.isIdentifier(p.key) && p.key.name === "component"
754
+ ) || node.properties.unshift(value);
755
+ return;
756
+ }
757
+ let [first, ...rest] = path, existing = node.properties.find(
758
+ (p) => t7.isObjectProperty(p) && t7.isIdentifier(p.key) && p.key.name === first && t7.isObjectExpression(p.value)
759
+ ), subNode;
760
+ existing ? subNode = existing.value : (subNode = t7.objectExpression([]), node.properties.push(t7.objectProperty(t7.identifier(first), subNode))), addComponentDescription(subNode, rest, value);
761
+ }, enrichCsfMeta = (csf, csfSource, options) => {
762
+ let description = !options?.disableDescription && extractDescription(csfSource._metaStatement);
763
+ if (description) {
764
+ let metaNode = csf._metaNode;
765
+ metaNode && !csf._metaNodeIsSynthetic && t7.isObjectExpression(metaNode) && addComponentDescription(
766
+ metaNode,
767
+ ["parameters", "docs", "description"],
768
+ t7.objectProperty(t7.identifier("component"), t7.stringLiteral(description))
769
+ );
770
+ }
771
+ }, enrichCsf = async (csf, csfSource, options) => {
772
+ enrichCsfMeta(csf, csfSource, options), await options?.enrichCsf?.(csf, csfSource), Object.keys(csf._storyExports).forEach((key) => {
773
+ enrichCsfStory(csf, csfSource, key, options);
774
+ });
775
+ }, extractSource = (node) => {
776
+ let src = t7.isVariableDeclarator(node) ? node.init : node, { code } = generate2(src, {});
777
+ return code;
778
+ }, extractDescription = (node) => node?.leadingComments ? node.leadingComments.map((comment) => comment.type === "CommentLine" || !comment.value.startsWith("*") ? null : comment.value.split(`
779
+ `).map((line) => line.replace(/^(\s+)?(\*+)?(\s)?/, "")).join(`
780
+ `).trim()).filter(Boolean).join(`
781
+ `) : "";
782
+
783
+ // ../../node_modules/comment-parser/es6/primitives.js
784
+ var Markers;
785
+ (function(Markers2) {
786
+ Markers2.start = "/**", Markers2.nostart = "/***", Markers2.delim = "*", Markers2.end = "*/";
787
+ })(Markers || (Markers = {}));
788
+
789
+ // ../../node_modules/comment-parser/es6/util.js
790
+ function isSpace(source) {
791
+ return /^\s+$/.test(source);
792
+ }
793
+ function splitCR(source) {
794
+ let matches = source.match(/\r+$/);
795
+ return matches == null ? ["", source] : [source.slice(-matches[0].length), source.slice(0, -matches[0].length)];
796
+ }
797
+ function splitSpace(source) {
798
+ let matches = source.match(/^\s+/);
799
+ return matches == null ? ["", source] : [source.slice(0, matches[0].length), source.slice(matches[0].length)];
800
+ }
801
+ function splitLines(source) {
802
+ return source.split(/\n/);
803
+ }
804
+ function seedSpec(spec = {}) {
805
+ return Object.assign({ tag: "", name: "", type: "", optional: !1, description: "", problems: [], source: [] }, spec);
806
+ }
807
+ function seedTokens(tokens = {}) {
808
+ return Object.assign({ start: "", delimiter: "", postDelimiter: "", tag: "", postTag: "", name: "", postName: "", type: "", postType: "", description: "", end: "", lineEnd: "" }, tokens);
809
+ }
810
+
811
+ // ../../node_modules/comment-parser/es6/parser/block-parser.js
812
+ var reTag = /^@[^\s/]+(?=\s|$)/;
813
+ function getParser({ fence = "```" } = {}) {
814
+ let fencer = getFencer(fence), toggleFence = (source, isFenced) => fencer(source) ? !isFenced : isFenced;
815
+ return function(source) {
816
+ let sections = [[]], isFenced = !1;
817
+ for (let line of source)
818
+ reTag.test(line.tokens.description) && !isFenced ? sections.push([line]) : sections[sections.length - 1].push(line), isFenced = toggleFence(line.tokens.description, isFenced);
819
+ return sections;
820
+ };
821
+ }
822
+ function getFencer(fence) {
823
+ return typeof fence == "string" ? (source) => source.split(fence).length % 2 === 0 : fence;
824
+ }
825
+
826
+ // ../../node_modules/comment-parser/es6/parser/source-parser.js
827
+ function getParser2({ startLine = 0, markers = Markers } = {}) {
828
+ let block = null, num = startLine;
829
+ return function(source) {
830
+ let rest = source, tokens = seedTokens();
831
+ if ([tokens.lineEnd, rest] = splitCR(rest), [tokens.start, rest] = splitSpace(rest), block === null && rest.startsWith(markers.start) && !rest.startsWith(markers.nostart) && (block = [], tokens.delimiter = rest.slice(0, markers.start.length), rest = rest.slice(markers.start.length), [tokens.postDelimiter, rest] = splitSpace(rest)), block === null)
832
+ return num++, null;
833
+ let isClosed = rest.trimEnd().endsWith(markers.end);
834
+ if (tokens.delimiter === "" && rest.startsWith(markers.delim) && !rest.startsWith(markers.end) && (tokens.delimiter = markers.delim, rest = rest.slice(markers.delim.length), [tokens.postDelimiter, rest] = splitSpace(rest)), isClosed) {
835
+ let trimmed = rest.trimEnd();
836
+ tokens.end = rest.slice(trimmed.length - markers.end.length), rest = trimmed.slice(0, -markers.end.length);
837
+ }
838
+ if (tokens.description = rest, block.push({ number: num, source, tokens }), num++, isClosed) {
839
+ let result = block.slice();
840
+ return block = null, result;
841
+ }
842
+ return null;
843
+ };
844
+ }
845
+
846
+ // ../../node_modules/comment-parser/es6/parser/spec-parser.js
847
+ function getParser3({ tokenizers }) {
848
+ return function(source) {
849
+ var _a;
850
+ let spec = seedSpec({ source });
851
+ for (let tokenize of tokenizers)
852
+ if (spec = tokenize(spec), !((_a = spec.problems[spec.problems.length - 1]) === null || _a === void 0) && _a.critical)
853
+ break;
854
+ return spec;
855
+ };
856
+ }
857
+
858
+ // ../../node_modules/comment-parser/es6/parser/tokenizers/tag.js
859
+ function tagTokenizer() {
860
+ return (spec) => {
861
+ let { tokens } = spec.source[0], match = tokens.description.match(/\s*(@(\S+))(\s*)/);
862
+ return match === null ? (spec.problems.push({
863
+ code: "spec:tag:prefix",
864
+ message: 'tag should start with "@" symbol',
865
+ line: spec.source[0].number,
866
+ critical: !0
867
+ }), spec) : (match[1].includes("/") || (tokens.tag = match[1], tokens.postTag = match[3], tokens.description = tokens.description.slice(match[0].length), spec.tag = match[2]), spec);
868
+ };
869
+ }
870
+
871
+ // ../../node_modules/comment-parser/es6/parser/tokenizers/type.js
872
+ function typeTokenizer(spacing = "compact") {
873
+ let join2 = getJoiner(spacing);
874
+ return (spec) => {
875
+ let curlies = 0, lines = [], descriptionBegun = !1, firstTypeIteration = !0;
876
+ for (let { tokens } of spec.source.values()) {
877
+ let type = "";
878
+ if (!descriptionBegun && tokens.description.trim())
879
+ descriptionBegun = !0;
880
+ else if (!descriptionBegun)
881
+ continue;
882
+ if (firstTypeIteration && tokens.description[0] !== "{")
883
+ return spec;
884
+ firstTypeIteration = !1;
885
+ for (let ch of tokens.description)
886
+ if (ch === "{" && curlies++, ch === "}" && curlies--, type += ch, curlies === 0)
887
+ break;
888
+ if (lines.push([tokens, type]), curlies === 0)
889
+ break;
890
+ }
891
+ if (!descriptionBegun)
892
+ return spec;
893
+ if (curlies !== 0)
894
+ return spec.problems.push({
895
+ code: "spec:type:unpaired-curlies",
896
+ message: "unpaired curlies",
897
+ line: spec.source[0].number,
898
+ critical: !0
899
+ }), spec;
900
+ let parts = [], offset = lines[0][0].postDelimiter.length;
901
+ for (let [i, [tokens, type]] of lines.entries())
902
+ tokens.type = type, i > 0 && (tokens.type = tokens.postDelimiter.slice(offset) + type, tokens.postDelimiter = tokens.postDelimiter.slice(0, offset)), [tokens.postType, tokens.description] = splitSpace(tokens.description.slice(type.length)), parts.push(tokens.type);
903
+ return parts[0] = parts[0].slice(1), parts[parts.length - 1] = parts[parts.length - 1].slice(0, -1), spec.type = join2(parts), spec;
904
+ };
905
+ }
906
+ var trim = (x) => x.trim();
907
+ function getJoiner(spacing) {
908
+ return spacing === "compact" ? (t13) => t13.map(trim).join("") : spacing === "preserve" ? (t13) => t13.join(`
909
+ `) : spacing;
910
+ }
911
+
912
+ // ../../node_modules/comment-parser/es6/parser/tokenizers/name.js
913
+ var isQuoted = (s) => s && s.startsWith('"') && s.endsWith('"');
914
+ function nameTokenizer() {
915
+ let typeEnd = (num, { tokens }, i) => tokens.type === "" ? num : i;
916
+ return (spec) => {
917
+ let finalTypeLine = spec.source.reduce(typeEnd, 0), tokens;
918
+ if (spec.type)
919
+ do {
920
+ if ({ tokens } = spec.source[finalTypeLine], tokens.description.trim())
921
+ break;
922
+ finalTypeLine++;
923
+ } while (spec.source[finalTypeLine]);
924
+ else
925
+ ({ tokens } = spec.source[finalTypeLine]);
926
+ let source = tokens.description.trimStart(), quotedGroups = source.split('"');
927
+ if (quotedGroups.length > 1 && quotedGroups[0] === "" && quotedGroups.length % 2 === 1)
928
+ return spec.name = quotedGroups[1], tokens.name = `"${quotedGroups[1]}"`, [tokens.postName, tokens.description] = splitSpace(source.slice(tokens.name.length)), spec;
929
+ let brackets = 0, name = "", optional = !1, defaultValue;
930
+ for (let ch of source) {
931
+ if (brackets === 0 && isSpace(ch))
932
+ break;
933
+ ch === "[" && brackets++, ch === "]" && brackets--, name += ch;
934
+ }
935
+ if (brackets !== 0)
936
+ return spec.problems.push({
937
+ code: "spec:name:unpaired-brackets",
938
+ message: "unpaired brackets",
939
+ line: spec.source[0].number,
940
+ critical: !0
941
+ }), spec;
942
+ let nameToken = name;
943
+ if (name[0] === "[" && name[name.length - 1] === "]") {
944
+ optional = !0, name = name.slice(1, -1);
945
+ let parts = name.split("=");
946
+ if (name = parts[0].trim(), parts[1] !== void 0 && (defaultValue = parts.slice(1).join("=").trim()), name === "")
947
+ return spec.problems.push({
948
+ code: "spec:name:empty-name",
949
+ message: "empty name",
950
+ line: spec.source[0].number,
951
+ critical: !0
952
+ }), spec;
953
+ if (defaultValue === "")
954
+ return spec.problems.push({
955
+ code: "spec:name:empty-default",
956
+ message: "empty default value",
957
+ line: spec.source[0].number,
958
+ critical: !0
959
+ }), spec;
960
+ if (!isQuoted(defaultValue) && /=(?!>)/.test(defaultValue || ""))
961
+ return spec.problems.push({
962
+ code: "spec:name:invalid-default",
963
+ message: "invalid default value syntax",
964
+ line: spec.source[0].number,
965
+ critical: !0
966
+ }), spec;
967
+ }
968
+ if (!optional) {
969
+ let eqIndex = name.search(/=(?!>)/);
970
+ if (eqIndex !== -1) {
971
+ let preEqual = name.slice(0, eqIndex).trim(), postEqual = name.slice(eqIndex + 1).trim();
972
+ if (preEqual === "")
973
+ return spec.problems.push({
974
+ code: "spec:name:empty-name",
975
+ message: "empty name",
976
+ line: spec.source[0].number,
977
+ critical: !0
978
+ }), spec;
979
+ if (postEqual === "")
980
+ return spec.problems.push({
981
+ code: "spec:name:empty-default",
982
+ message: "empty default value",
983
+ line: spec.source[0].number,
984
+ critical: !0
985
+ }), spec;
986
+ if (/^[\p{ID_Start}$_\.][\p{ID_Continue}$_\u200c\u200d\.]*=/u.test(name)) {
987
+ if (!isQuoted(postEqual) && /=(?!>)/.test(postEqual))
988
+ return spec.problems.push({
989
+ code: "spec:name:invalid-default",
990
+ message: "invalid default value syntax",
991
+ line: spec.source[0].number,
992
+ critical: !0
993
+ }), spec;
994
+ name = preEqual, defaultValue = postEqual;
995
+ }
996
+ }
997
+ }
998
+ return spec.optional = optional, spec.name = name, tokens.name = nameToken, defaultValue !== void 0 && (spec.default = defaultValue), [tokens.postName, tokens.description] = splitSpace(source.slice(tokens.name.length)), spec;
999
+ };
1000
+ }
1001
+
1002
+ // ../../node_modules/comment-parser/es6/parser/tokenizers/description.js
1003
+ function descriptionTokenizer(spacing = "compact", markers = Markers) {
1004
+ let join2 = getJoiner2(spacing);
1005
+ return (spec) => (spec.description = join2(spec.source, markers), spec);
1006
+ }
1007
+ function getJoiner2(spacing) {
1008
+ return spacing === "compact" ? compactJoiner : spacing === "preserve" ? preserveJoiner : spacing;
1009
+ }
1010
+ function compactJoiner(lines, markers = Markers) {
1011
+ return lines.map(({ tokens: { description } }) => description.trim()).filter((description) => description !== "").join(" ");
1012
+ }
1013
+ var lineNo = (num, { tokens }, i) => tokens.type === "" ? num : i, getDescription = ({ tokens }) => (tokens.delimiter === "" ? tokens.start : tokens.postDelimiter.slice(1)) + tokens.description;
1014
+ function preserveJoiner(lines, markers = Markers) {
1015
+ if (lines.length === 0)
1016
+ return "";
1017
+ lines[0].tokens.description === "" && lines[0].tokens.delimiter === markers.start && (lines = lines.slice(1));
1018
+ let lastLine = lines[lines.length - 1];
1019
+ return lastLine !== void 0 && lastLine.tokens.description === "" && lastLine.tokens.end.endsWith(markers.end) && (lines = lines.slice(0, -1)), lines = lines.slice(lines.reduce(lineNo, 0)), lines.map(getDescription).join(`
1020
+ `);
1021
+ }
1022
+
1023
+ // ../../node_modules/comment-parser/es6/parser/index.js
1024
+ function getParser4({ startLine = 0, fence = "```", spacing = "compact", markers = Markers, tokenizers = [
1025
+ tagTokenizer(),
1026
+ typeTokenizer(spacing),
1027
+ nameTokenizer(),
1028
+ descriptionTokenizer(spacing)
1029
+ ] } = {}) {
1030
+ if (startLine < 0 || startLine % 1 > 0)
1031
+ throw new Error("Invalid startLine");
1032
+ let parseSource = getParser2({ startLine, markers }), parseBlock = getParser({ fence }), parseSpec = getParser3({ tokenizers }), joinDescription = getJoiner2(spacing);
1033
+ return function(source) {
1034
+ let blocks = [];
1035
+ for (let line of splitLines(source)) {
1036
+ let lines = parseSource(line);
1037
+ if (lines === null)
1038
+ continue;
1039
+ let sections = parseBlock(lines), specs = sections.slice(1).map(parseSpec);
1040
+ blocks.push({
1041
+ description: joinDescription(sections[0], markers),
1042
+ tags: specs,
1043
+ source: lines,
1044
+ problems: specs.reduce((acc, spec) => acc.concat(spec.problems), [])
1045
+ });
1046
+ }
1047
+ return blocks;
1048
+ };
1049
+ }
1050
+
1051
+ // ../../node_modules/comment-parser/es6/stringifier/index.js
1052
+ function join(tokens) {
1053
+ return tokens.start + tokens.delimiter + tokens.postDelimiter + tokens.tag + tokens.postTag + tokens.type + tokens.postType + tokens.name + tokens.postName + tokens.description + tokens.end + tokens.lineEnd;
1054
+ }
1055
+ function getStringifier() {
1056
+ return (block) => block.source.map(({ tokens }) => join(tokens)).join(`
1057
+ `);
1058
+ }
1059
+
1060
+ // ../../node_modules/comment-parser/es6/stringifier/inspect.js
1061
+ var zeroWidth = {
1062
+ line: 0,
1063
+ start: 0,
1064
+ delimiter: 0,
1065
+ postDelimiter: 0,
1066
+ tag: 0,
1067
+ postTag: 0,
1068
+ name: 0,
1069
+ postName: 0,
1070
+ type: 0,
1071
+ postType: 0,
1072
+ description: 0,
1073
+ end: 0,
1074
+ lineEnd: 0
1075
+ };
1076
+ var fields = Object.keys(zeroWidth);
1077
+
1078
+ // ../../node_modules/comment-parser/es6/index.js
1079
+ function parse(source, options = {}) {
1080
+ return getParser4(options)(source);
1081
+ }
1082
+ var stringify = getStringifier();
1083
+
1084
+ // src/csf-tools/jsdoc.ts
1085
+ function groupByTag(specs) {
1086
+ let groups = /* @__PURE__ */ new Map();
1087
+ for (let spec of specs) {
1088
+ let group = groups.get(spec.tag);
1089
+ group ? group.push(spec) : groups.set(spec.tag, [spec]);
1090
+ }
1091
+ return groups;
1092
+ }
1093
+ function hasTags(tags) {
1094
+ return !!tags && Object.keys(tags).length > 0;
1095
+ }
1096
+ function mergeTags(docgenJsDocTags, extractedTags) {
1097
+ return hasTags(docgenJsDocTags) ? { ...extractedTags ?? {}, ...docgenJsDocTags } : extractedTags ?? {};
1098
+ }
1099
+ function extractJSDocInfo(jsdocComment) {
1100
+ let jsDoc = ["/**", ...jsdocComment.split(`
1101
+ `).map((line) => ` * ${line}`), " */"].join(`
1102
+ `), description = parse(jsDoc, { spacing: "preserve" })[0].description, parsed = parse(jsDoc, { spacing: "compact" });
1103
+ return {
1104
+ description,
1105
+ tags: Object.fromEntries(
1106
+ Array.from(groupByTag(parsed[0].tags), ([tag, specs]) => [
1107
+ tag,
1108
+ specs.map(
1109
+ (spec) => ((spec.type ? `{${spec.type}} ` : "") + `${spec.name} ${spec.description}`).trim()
1110
+ )
1111
+ ])
1112
+ )
1113
+ };
1114
+ }
1115
+ function extractComponentDescription(metaJsDoc, docgenDescription, docgenJsDocTags) {
1116
+ let jsdocComment = metaJsDoc || docgenDescription, extracted = jsdocComment ? extractJSDocInfo(jsdocComment) : void 0, tags = mergeTags(docgenJsDocTags, extracted?.tags), description = extracted?.description;
1117
+ return {
1118
+ description: ((tags?.describe?.[0] || tags?.desc?.[0]) ?? description)?.trim(),
1119
+ summary: tags.summary?.[0],
1120
+ jsDocTags: tags
1121
+ };
1122
+ }
1123
+
1124
+ // src/csf-tools/story-shape/jsdoc.ts
1125
+ function jsDocTagsForPath(path) {
1126
+ let statement = path?.getStatementParent(), jsdocComment = statement ? extractDescription(statement.node) : "";
1127
+ return jsdocComment ? extractJSDocInfo(jsdocComment).tags ?? {} : {};
1128
+ }
1129
+ function extractStoryJSDocInfo(storyStatement) {
1130
+ let { description, summary } = extractComponentDescription(
1131
+ extractDescription(storyStatement) || void 0,
1132
+ void 0
1133
+ );
1134
+ return { description, summary };
1135
+ }
1136
+
1137
+ // src/csf-tools/story-shape/normalize-story.ts
1138
+ function normalizeStoryDeclaration(storyDeclaration) {
1139
+ let storyPath = declarationExpression(storyDeclaration), resolvedStoryPath = resolveLocalStory(storyDeclaration, storyPath), normalizedPath = bindInitializer(storyDeclaration, resolvedStoryPath) ?? factoryArgumentExpression(resolvedStoryPath), unwrappedPath = unwrapTypeExpression(normalizedPath);
1140
+ return classifyStoryPath(unwrappedPath);
1141
+ }
1142
+ function resolveLocalStory(declaration, expression) {
1143
+ let visited = /* @__PURE__ */ new Set(), current = unwrapTypeExpression(expression);
1144
+ for (; current.isIdentifier(); ) {
1145
+ let name = current.node.name;
1146
+ if (visited.has(name) || !current.scope.getBinding(name)?.constant)
1147
+ break;
1148
+ visited.add(name);
1149
+ let resolved = resolveIdentifierInit(declaration, current);
1150
+ if (!resolved)
1151
+ break;
1152
+ current = unwrapTypeExpression(resolved);
1153
+ }
1154
+ return current;
1155
+ }
1156
+ function declarationExpression(storyDeclaration) {
1157
+ if (storyDeclaration.isFunctionDeclaration())
1158
+ return storyDeclaration;
1159
+ if (storyDeclaration.isVariableDeclarator()) {
1160
+ let init = storyDeclaration.get("init");
1161
+ if (!init.isExpression())
1162
+ throw storyDeclaration.buildCodeFrameError("Expected story initializer to be an expression");
1163
+ return init;
1164
+ }
1165
+ throw storyDeclaration.buildCodeFrameError(
1166
+ "Expected story to be a function or variable declaration"
1167
+ );
1168
+ }
1169
+ function bindInitializer(storyDeclaration, storyPath) {
1170
+ if (!storyPath.isCallExpression() || !isCanonicalCsf2BindCall(storyPath.node))
1171
+ return null;
1172
+ let callee = storyPath.get("callee");
1173
+ if (!callee.isMemberExpression())
1174
+ return null;
1175
+ let obj = callee.get("object");
1176
+ return obj.isIdentifier() ? resolveIdentifierInit(storyDeclaration, obj) : null;
1177
+ }
1178
+ function factoryArgumentExpression(storyPath) {
1179
+ if (!storyPath.isCallExpression() || !isCsfFactoryCall(storyPath.node))
1180
+ return storyPath;
1181
+ let args = storyPath.get("arguments");
1182
+ if (args.length === 0)
1183
+ return storyPath;
1184
+ if (args.length !== 1 || !args[0].isExpression())
1185
+ throw storyPath.buildCodeFrameError("Could not evaluate story expression");
1186
+ return args[0];
1187
+ }
1188
+ function unwrapTypeExpression(storyPath) {
1189
+ return storyPath.isTSSatisfiesExpression() || storyPath.isTSAsExpression() ? storyPath.get("expression") : storyPath;
1190
+ }
1191
+ function classifyStoryPath(storyPath) {
1192
+ if (storyPath.isObjectExpression())
1193
+ return { type: "config", path: storyPath };
1194
+ if (storyPath.isArrowFunctionExpression() || storyPath.isFunctionExpression() || storyPath.isFunctionDeclaration())
1195
+ return { type: "fn", path: storyPath };
1196
+ if (storyPath.isCallExpression() && isCsfFactoryCall(storyPath.node) && storyPath.node.arguments.length === 0)
1197
+ return { type: "emptyConfig", path: storyPath };
1198
+ throw storyPath.buildCodeFrameError(
1199
+ "Expected story to be csf factory, function or an object expression"
1200
+ );
1201
+ }
1202
+
1203
+ // src/csf-tools/story-shape/resolve-story-args.ts
1204
+ import { types as t8 } from "@aussieljk/forkbook/internal/babel";
1205
+ function createStoryArgsResolver(csf, references) {
1206
+ let ctx = {
1207
+ program: csf._file.path,
1208
+ filePath: csf._file.opts.filename ?? "",
1209
+ ...references
1210
+ }, metaNode = csf._metaNode, metaMembers = metaNode && t8.isObjectExpression(metaNode) ? resolveObjectMembers(metaNode, ctx) : { properties: {}, shadowed: [], unresolved: [] }, metaArgs = resolveArgsRecord(metaMembers.properties.args, ctx);
1211
+ return {
1212
+ ctx,
1213
+ resolve: (storyExport) => {
1214
+ let localName = csf._stories[storyExport]?.localName ?? storyExport, storyMembers = resolveBindingMembers(ctx, localName) ?? {
1215
+ properties: {},
1216
+ shadowed: [],
1217
+ unresolved: [sourceOf(csf._storyStatements[storyExport] ?? t8.identifier(storyExport))]
1218
+ }, storyArgs = resolveArgsRecord(storyMembers.properties.args, ctx), args = {}, imports = [], unresolved = [
1219
+ ...metaMembers.unresolved,
1220
+ ...metaArgs.unresolved,
1221
+ ...storyMembers.unresolved,
1222
+ ...storyArgs.unresolved
1223
+ ];
1224
+ for (let [key, node] of Object.entries({
1225
+ ...metaArgs.properties,
1226
+ ...storyArgs.properties
1227
+ })) {
1228
+ let value = resolveArgValue(node, ctx);
1229
+ args[key] = value.node, imports.push(...value.imports), unresolved.push(...value.unresolved);
1230
+ }
1231
+ return { args, imports, unresolved, storyMembers, metaMembers };
1232
+ }
1233
+ };
1234
+ }
1235
+ var unresolvedWarning = (unresolved) => {
1236
+ let sources = [...new Set(unresolved)];
1237
+ return sources.length === 0 ? void 0 : `Incomplete snippet: ${sources.map((source) => `\`${source}\``).join(", ")} could not be resolved statically.`;
1238
+ }, noSnippetWarning = (unresolved) => {
1239
+ let sources = [...new Set(unresolved)];
1240
+ return sources.length === 0 ? void 0 : `No static snippet: ${sources.map((source) => `\`${source}\``).join(", ")} could not be resolved statically.`;
1241
+ };
1242
+
1243
+ // src/csf-tools/story-shape/render.ts
1244
+ var isRenderFunction = (path) => path.isArrowFunctionExpression() || path.isFunctionExpression() || path.isFunctionDeclaration();
1245
+ function resolveRenderFunction(config, storyDeclaration, references) {
1246
+ let properties = config?.get("properties") ?? [], renderIndex = -1;
1247
+ for (let index = properties.length - 1; index >= 0; index -= 1) {
1248
+ let property = properties[index];
1249
+ if ((property.isObjectProperty() || property.isObjectMethod()) && keyOf(property.node) === "render") {
1250
+ renderIndex = index;
1251
+ break;
1252
+ }
1253
+ }
1254
+ let throughSpreads = () => config && references ? renderFromMembers(
1255
+ resolveObjectMembers(config.node, references),
1256
+ references,
1257
+ storyDeclaration
1258
+ ) : { kind: "unresolved" };
1259
+ if (renderIndex === -1)
1260
+ return properties.some((property) => property.isSpreadElement()) ? throughSpreads() : { kind: "missing" };
1261
+ let resolved = readRenderProperty(properties[renderIndex], storyDeclaration);
1262
+ if (resolved.kind === "invalid")
1263
+ throw resolved.path.buildCodeFrameError(
1264
+ "Expected render to be an arrow function or function expression"
1265
+ );
1266
+ if (properties.some((property, index) => index > renderIndex && property.isSpreadElement())) {
1267
+ let read = throughSpreads();
1268
+ return read.kind !== "unresolved" ? read : resolved.kind === "resolved" ? { kind: "unresolved", shadowedRender: resolved.path } : { kind: "unresolved" };
1269
+ }
1270
+ return resolved;
1271
+ }
1272
+ function resolveEffectiveRender(csf, exportName, references) {
1273
+ let declaration = csf._storyDeclarationPath[exportName], normalized = normalizeStoryDeclarationForRender(declaration);
1274
+ if (normalized.type === "fn")
1275
+ return { kind: "resolved", path: normalized.path };
1276
+ let storyRender = readRender(
1277
+ normalized.type === "config" ? normalized.path : void 0,
1278
+ declaration,
1279
+ references
1280
+ );
1281
+ if (storyRender.kind === "invalid")
1282
+ return { kind: "unresolved" };
1283
+ if (storyRender.kind !== "missing")
1284
+ return storyRender;
1285
+ let metaRender = readRender(metaObjectPath(csf), declaration, references);
1286
+ return metaRender.kind === "invalid" ? { kind: "unresolved" } : metaRender;
1287
+ }
1288
+ var normalizeStoryDeclarationForRender = normalizeStoryDeclaration, readRender = (config, storyDeclaration, references) => {
1289
+ let properties = config?.get("properties") ?? [], renderIndex = -1;
1290
+ for (let index = properties.length - 1; index >= 0; index -= 1) {
1291
+ let property = properties[index];
1292
+ if ((property.isObjectProperty() || property.isObjectMethod()) && keyOf(property.node) === "render") {
1293
+ renderIndex = index;
1294
+ break;
1295
+ }
1296
+ }
1297
+ let throughSpreads = () => config && references ? renderFromMembers(
1298
+ resolveObjectMembers(config.node, references),
1299
+ references,
1300
+ storyDeclaration
1301
+ ) : { kind: "unresolved" };
1302
+ if (renderIndex === -1)
1303
+ return properties.some((property) => property.isSpreadElement()) ? throughSpreads() : { kind: "missing" };
1304
+ let resolved = readRenderProperty(properties[renderIndex], storyDeclaration);
1305
+ if (properties.some((property, index) => index > renderIndex && property.isSpreadElement())) {
1306
+ let read = throughSpreads();
1307
+ return read.kind !== "unresolved" ? read : resolved.kind === "resolved" ? { kind: "unresolved", shadowedRender: resolved.path } : { kind: "unresolved" };
1308
+ }
1309
+ return resolved;
1310
+ };
1311
+ function renderFromMembers(members, references, storyDeclaration) {
1312
+ if (members.unresolved.length > 0)
1313
+ return { kind: "unresolved" };
1314
+ let node = members.properties.render;
1315
+ if (node === void 0)
1316
+ return { kind: "missing" };
1317
+ let path = pathForNode(references.program, node);
1318
+ if (!path)
1319
+ return { kind: "unresolved" };
1320
+ if (path.isObjectMethod())
1321
+ return path.node.kind === "method" && !path.node.generator ? { kind: "resolved", path } : { kind: "unresolved" };
1322
+ if (path.isIdentifier()) {
1323
+ let resolved = resolveIdentifierInit(storyDeclaration, path);
1324
+ return resolved && isRenderFunction(resolved) ? { kind: "resolved", path: resolved } : { kind: "unresolved" };
1325
+ }
1326
+ return isRenderFunction(path) ? { kind: "resolved", path } : { kind: "unresolved" };
1327
+ }
1328
+ function readRenderProperty(renderProperty, storyDeclaration) {
1329
+ if (renderProperty.isObjectMethod())
1330
+ return renderProperty.node.kind === "method" && !renderProperty.node.generator ? { kind: "resolved", path: renderProperty } : { kind: "unresolved" };
1331
+ let renderPath = renderProperty.get("value");
1332
+ if (renderPath.isIdentifier()) {
1333
+ let resolved = resolveIdentifierInit(storyDeclaration, renderPath);
1334
+ return resolved && isRenderFunction(resolved) ? { kind: "resolved", path: resolved } : { kind: "unresolved" };
1335
+ }
1336
+ return isRenderFunction(renderPath) ? { kind: "resolved", path: renderPath } : { kind: "invalid", path: renderPath };
1337
+ }
1338
+
1339
+ // src/csf-tools/story-shape/reference-context.ts
1340
+ import { readFileSync } from "node:fs";
1341
+
1342
+ // src/csf-tools/CsfFile.ts
1343
+ import { readFile, writeFile } from "node:fs/promises";
1344
+ import {
1345
+ BabelFileClass,
1346
+ babelParse as babelParse2,
1347
+ generate as generate3,
1348
+ recast,
1349
+ types as t12,
1350
+ traverse as traverse2
1351
+ } from "@aussieljk/forkbook/internal/babel";
1352
+ import {
1353
+ isExportStory,
1354
+ storyNameFromExport,
1355
+ toId,
1356
+ toTestId
1357
+ } from "@aussieljk/forkbook/internal/csf/csf-utils";
1358
+ import { logger } from "@aussieljk/forkbook/internal/node-logger";
1359
+ import { dedent } from "ts-dedent";
1360
+
1361
+ // src/csf-tools/CsfObjectDiscovery.ts
1362
+ import { types as t10 } from "@aussieljk/forkbook/internal/babel";
1363
+
1364
+ // src/csf-tools/CsfObject.ts
1365
+ import { types as t9 } from "@aussieljk/forkbook/internal/babel";
1366
+ var UNRESOLVED = /* @__PURE__ */ Symbol("unresolved"), staticKey = (member) => {
1367
+ if (t9.isStringLiteral(member.key))
1368
+ return member.key.value;
1369
+ if (t9.isNumericLiteral(member.key))
1370
+ return String(member.key.value);
1371
+ if (t9.isIdentifier(member.key) && !member.computed)
1372
+ return member.key.name;
1373
+ if (t9.isTemplateLiteral(member.key) && member.key.expressions.length === 0)
1374
+ return member.key.quasis[0]?.value.cooked ?? member.key.quasis[0]?.value.raw;
1375
+ }, keyNode = (name) => t9.isValidIdentifier(name) ? t9.identifier(name) : t9.stringLiteral(name), unsafePath = (path) => path.includes("__proto__"), lookupProperty = (object, name, removing = !1) => {
1376
+ let matches = [], unknown, unknownAfterMatch;
1377
+ for (let member of object.properties) {
1378
+ let key = t9.isSpreadElement(member) ? void 0 : staticKey(member);
1379
+ if (key === void 0) {
1380
+ unknown = {
1381
+ code: t9.isSpreadElement(member) ? "spread-field" : "dynamic-key",
1382
+ node: member
1383
+ }, matches.length > 0 && (unknownAfterMatch = unknown);
1384
+ continue;
1385
+ }
1386
+ if (key === name) {
1387
+ if (!t9.isObjectProperty(member) && !t9.isObjectMethod(member, { kind: "method" }))
1388
+ return { ok: !1, code: "unsupported-member", node: member };
1389
+ matches.push(member);
1390
+ }
1391
+ }
1392
+ if (matches.length > 1)
1393
+ return { ok: !1, code: "duplicate-field", node: matches[1] };
1394
+ let unproven = unknownAfterMatch ?? (removing || matches.length === 0 ? unknown : void 0);
1395
+ return unproven ? { ok: !1, code: unproven.code, node: unproven.node } : { ok: !0, property: matches[0] };
1396
+ }, propertyExpression = (property) => {
1397
+ if (t9.isObjectProperty(property))
1398
+ return t9.isExpression(property.value) ? property.value : void 0;
1399
+ let value = t9.functionExpression(
1400
+ null,
1401
+ property.params,
1402
+ property.body,
1403
+ property.generator,
1404
+ property.async
1405
+ );
1406
+ return value.returnType = property.returnType, value.typeParameters = property.typeParameters, value;
1407
+ }, isEvaluationInert = (node) => {
1408
+ let value = unwrapExpression(node);
1409
+ return t9.isTemplateLiteral(value) ? value.expressions.length === 0 : t9.isLiteral(value) || t9.isFunctionExpression(value) || t9.isArrowFunctionExpression(value) ? !0 : t9.isUnaryExpression(value) ? ["!", "void", "typeof"].includes(value.operator) ? isEvaluationInert(value.argument) : t9.isNumericLiteral(unwrapExpression(value.argument)) : t9.isArrayExpression(value) ? value.elements.every((element) => element === null || isEvaluationInert(element)) : t9.isObjectExpression(value) ? value.properties.every(
1410
+ (property) => t9.isObjectProperty(property) && !property.computed && staticKey(property) !== void 0 && isEvaluationInert(property.value)
1411
+ ) : !1;
1412
+ }, CsfObjectEditor = class {
1413
+ constructor(target, root, prefix, reportDiagnostic, markChanged) {
1414
+ this.target = target;
1415
+ this.root = root;
1416
+ this.prefix = prefix;
1417
+ this.reportDiagnostic = reportDiagnostic;
1418
+ this.markChanged = markChanged;
1419
+ }
1420
+ #changed = !1;
1421
+ get changed() {
1422
+ return this.#changed;
1423
+ }
1424
+ get(path) {
1425
+ let value = this.getExpression(path);
1426
+ return value ? t9.cloneNode(value, !0) : void 0;
1427
+ }
1428
+ getValue(path) {
1429
+ let expression = this.getExpression(path);
1430
+ if (!expression)
1431
+ return;
1432
+ let value = this.readValue(expression);
1433
+ if (value === UNRESOLVED) {
1434
+ this.failure("unsupported-value", path, expression);
1435
+ return;
1436
+ }
1437
+ return value;
1438
+ }
1439
+ getExpression(path) {
1440
+ let logicalPath = this.normalizePath(path);
1441
+ if (!logicalPath)
1442
+ return;
1443
+ if (logicalPath.length === 0)
1444
+ return this.prefix.length > 0 ? this.root.node : void 0;
1445
+ let found = this.inspect(logicalPath);
1446
+ if (found.ok === !1) {
1447
+ this.failure(found.code, path, found.node);
1448
+ return;
1449
+ }
1450
+ return found.property && propertyExpression(found.property);
1451
+ }
1452
+ set(path, value) {
1453
+ let logicalPath = this.normalizePath(path);
1454
+ if (!logicalPath || logicalPath.length === 0 || unsafePath(logicalPath))
1455
+ return this.failure("unsupported-member", path, this.root.node);
1456
+ let inspected = this.inspect(logicalPath);
1457
+ if (inspected.ok === !1)
1458
+ return this.failure(inspected.code, path, inspected.node);
1459
+ if (t9.isObjectProperty(inspected.property) && inspected.property.value === value)
1460
+ return { ok: !0, changed: !1 };
1461
+ let expression = t9.isNode(value) && t9.isExpression(value) ? t9.cloneNode(value, !0) : t9.valueToNode(value);
1462
+ return inspected.property && inspected.parent ? this.replaceValue(inspected.property, inspected.parent, expression) : this.insert(logicalPath, t9.objectProperty(keyNode(logicalPath.at(-1)), expression)), this.success();
1463
+ }
1464
+ transform(path, derive) {
1465
+ let logicalPath = this.normalizePath(path);
1466
+ if (!logicalPath || logicalPath.length === 0 || unsafePath(logicalPath))
1467
+ return this.failure("unsupported-member", path, this.root.node);
1468
+ let inspected = this.inspect(logicalPath);
1469
+ if (inspected.ok === !1)
1470
+ return this.failure(inspected.code, path, inspected.node);
1471
+ let { property, parent } = inspected, value = property && propertyExpression(property);
1472
+ if (!property || !parent || !value)
1473
+ return { ok: !0, changed: !1 };
1474
+ let derived = derive(value);
1475
+ return !derived || derived === value ? { ok: !0, changed: !1 } : (this.replaceValue(property, parent, derived), this.success());
1476
+ }
1477
+ remove(path) {
1478
+ let logicalPath = this.normalizePath(path);
1479
+ if (!logicalPath || logicalPath.length === 0 || unsafePath(logicalPath))
1480
+ return this.failure("unsupported-member", path, this.root.node);
1481
+ let inspected = this.inspect(logicalPath);
1482
+ if (inspected.ok === !1)
1483
+ return this.failure(inspected.code, path, inspected.node);
1484
+ if (!inspected.property || !inspected.parent)
1485
+ return { ok: !0, changed: !1 };
1486
+ let removal = lookupProperty(inspected.parent, logicalPath.at(-1), !0);
1487
+ return removal.ok ? (inspected.parent.properties.splice(inspected.parent.properties.indexOf(inspected.property), 1), this.removeEmptyParents(logicalPath), this.success()) : this.failure(removal.code, path, removal.node);
1488
+ }
1489
+ rename(path, name) {
1490
+ let destination = [...path.slice(0, -1), name];
1491
+ return this.move(path, destination);
1492
+ }
1493
+ move(from, to) {
1494
+ let sourcePath = this.normalizePath(from), destinationPath = this.normalizePath(to);
1495
+ if (!sourcePath || !destinationPath || sourcePath.length === 0 || destinationPath.length === 0 || unsafePath(sourcePath) || unsafePath(destinationPath))
1496
+ return this.failure("unsupported-member", sourcePath ? to : from, this.root.node);
1497
+ if (sourcePath.length === destinationPath.length && sourcePath.every((part, index) => destinationPath[index] === part))
1498
+ return { ok: !0, changed: !1 };
1499
+ if (destinationPath.length > sourcePath.length && sourcePath.every((part, index) => destinationPath[index] === part))
1500
+ return this.failure("cyclic-move", to, this.root.node);
1501
+ let source = this.inspect(sourcePath);
1502
+ if (source.ok === !1)
1503
+ return this.failure(source.code, from, source.node);
1504
+ if (!source.property || !source.parent)
1505
+ return { ok: !0, changed: !1 };
1506
+ let removal = lookupProperty(source.parent, sourcePath.at(-1), !0);
1507
+ if (!removal.ok)
1508
+ return this.failure(removal.code, from, removal.node);
1509
+ let destination = this.inspect(destinationPath);
1510
+ if (destination.ok === !1)
1511
+ return this.failure(destination.code, to, destination.node);
1512
+ if (destination.property)
1513
+ return this.failure("occupied-destination", to, destination.property);
1514
+ let sourceParent = sourcePath.slice(0, -1), destinationParent = destinationPath.slice(0, -1);
1515
+ return sourceParent.length === destinationParent.length && sourceParent.every((part, index) => destinationParent[index] === part) ? (t9.isObjectProperty(source.property) && (source.property.shorthand = !1), source.property.key = keyNode(destinationPath.at(-1)), source.property.computed = !1, this.success()) : (source.parent.properties.splice(source.parent.properties.indexOf(source.property), 1), t9.isObjectProperty(source.property) && (source.property.shorthand = !1), source.property.key = keyNode(destinationPath.at(-1)), source.property.computed = !1, this.insert(destinationPath, source.property), this.removeEmptyParents(sourcePath), this.success());
1516
+ }
1517
+ group(path, names) {
1518
+ let logicalPath = this.normalizePath(path);
1519
+ if (!logicalPath || logicalPath.length === 0 || unsafePath(logicalPath) || unsafePath(names))
1520
+ return this.failure("unsupported-member", path, this.root.node);
1521
+ let group = logicalPath.at(-1);
1522
+ if (names.includes(group))
1523
+ return this.failure("cyclic-move", path, this.root.node);
1524
+ let parent = this.root.node;
1525
+ if (logicalPath.length > 1) {
1526
+ let inspected = this.inspect(logicalPath.slice(0, -1));
1527
+ if (inspected.ok === !1)
1528
+ return this.failure(inspected.code, path, inspected.node);
1529
+ if (!inspected.property)
1530
+ return { ok: !0, changed: !1 };
1531
+ let value = t9.isObjectProperty(inspected.property) ? this.resolveExpression(inspected.property.value) : void 0;
1532
+ if (!t9.isObjectExpression(value))
1533
+ return this.failure("unsupported-member", path, inspected.property);
1534
+ parent = value;
1535
+ }
1536
+ let moved = parent.properties.filter(
1537
+ (property) => !t9.isSpreadElement(property) && names.includes(staticKey(property) ?? "")
1538
+ );
1539
+ if (moved.length === 0)
1540
+ return { ok: !0, changed: !1 };
1541
+ for (let property of parent.properties)
1542
+ if (t9.isSpreadElement(property) || property.computed || staticKey(property) === void 0)
1543
+ return this.failure(
1544
+ t9.isSpreadElement(property) ? "spread-field" : "dynamic-key",
1545
+ path,
1546
+ property,
1547
+ `the configuration contains ${t9.isSpreadElement(property) ? "a spread property" : "a computed property"}`
1548
+ );
1549
+ let sourceNames = /* @__PURE__ */ new Set();
1550
+ for (let property of moved) {
1551
+ let name = staticKey(property);
1552
+ if (!t9.isObjectProperty(property) || !t9.isExpression(property.value))
1553
+ return this.failure(
1554
+ "unsupported-member",
1555
+ path,
1556
+ property,
1557
+ `the top-level ${name} ${group} option is a method or accessor, not a movable value property`
1558
+ );
1559
+ if (sourceNames.has(name))
1560
+ return this.failure("duplicate-field", path, property);
1561
+ sourceNames.add(name);
1562
+ }
1563
+ let destination = lookupProperty(parent, group);
1564
+ if (destination.ok === !1)
1565
+ return this.failure(
1566
+ destination.code,
1567
+ path,
1568
+ destination.node,
1569
+ destination.code === "duplicate-field" ? `the configuration defines ${group} more than once` : `the existing ${group} value is not an object literal`
1570
+ );
1571
+ if (destination.property) {
1572
+ let existing = destination.property, value = t9.isObjectProperty(existing) ? unwrapExpression(existing.value) : void 0;
1573
+ if (!t9.isObjectExpression(value))
1574
+ return this.failure(
1575
+ "unsupported-member",
1576
+ path,
1577
+ existing,
1578
+ `the existing ${group} value is not an object literal`
1579
+ );
1580
+ for (let property of value.properties) {
1581
+ if (t9.isSpreadElement(property) || property.computed || staticKey(property) === void 0)
1582
+ return this.failure(
1583
+ t9.isSpreadElement(property) ? "spread-field" : "dynamic-key",
1584
+ path,
1585
+ property,
1586
+ `the existing ${group} object contains ${t9.isSpreadElement(property) ? "a spread property" : "a computed property"}`
1587
+ );
1588
+ if (!t9.isObjectProperty(property) || !t9.isExpression(property.value))
1589
+ return this.failure(
1590
+ "unsupported-member",
1591
+ path,
1592
+ property,
1593
+ `the existing ${group} object contains a method or accessor`
1594
+ );
1595
+ }
1596
+ let existingNames = new Set(
1597
+ value.properties.map(
1598
+ (property) => t9.isSpreadElement(property) ? void 0 : staticKey(property)
1599
+ )
1600
+ );
1601
+ for (let property of moved) {
1602
+ let name = staticKey(property);
1603
+ if (existingNames.has(name))
1604
+ return this.failure(
1605
+ "occupied-destination",
1606
+ path,
1607
+ property,
1608
+ `the ${name} option exists at both top level and inside ${group}, where the nested value is authoritative`
1609
+ );
1610
+ if (!t9.isObjectProperty(property) || !isEvaluationInert(property.value))
1611
+ return this.failure(
1612
+ "evaluation-order",
1613
+ path,
1614
+ property,
1615
+ `the ${name} option has a ${t9.isObjectProperty(property) ? unwrapExpression(property.value).type : "non-expression"} value whose relocation into the existing ${group} object could change expression evaluation order`
1616
+ );
1617
+ }
1618
+ value.properties.unshift(...moved);
1619
+ let movedSet = new Set(moved);
1620
+ parent.properties = parent.properties.filter((property) => !movedSet.has(property));
1621
+ } else {
1622
+ if (parent === this.root.node && this.root.detached) {
1623
+ let effectful = moved.find(
1624
+ (property) => !t9.isObjectProperty(property) || !isEvaluationInert(property.value)
1625
+ );
1626
+ if (effectful)
1627
+ return this.failure(
1628
+ "evaluation-order",
1629
+ path,
1630
+ effectful,
1631
+ "Grouping named config exports could change initializer evaluation order"
1632
+ );
1633
+ }
1634
+ let first = parent.properties.indexOf(moved[0]);
1635
+ if (parent.properties.indexOf(moved.at(-1)) - first + 1 !== moved.length)
1636
+ return this.failure(
1637
+ "evaluation-order",
1638
+ path,
1639
+ moved[1] ?? moved[0],
1640
+ `the top-level ${group} options are not contiguous, so grouping them could change expression evaluation order`
1641
+ );
1642
+ parent.properties.splice(
1643
+ first,
1644
+ moved.length,
1645
+ t9.objectProperty(keyNode(group), t9.objectExpression(moved))
1646
+ );
1647
+ }
1648
+ return this.success();
1649
+ }
1650
+ replaceValue(property, parent, value) {
1651
+ t9.isObjectProperty(property) ? (property.value = value, property.shorthand = !1) : t9.isFunctionExpression(value) && !value.id ? (property.params = value.params, property.body = value.body, property.async = value.async, property.generator = value.generator, property.returnType = value.returnType, property.typeParameters = value.typeParameters) : parent.properties.splice(
1652
+ parent.properties.indexOf(property),
1653
+ 1,
1654
+ t9.inheritsComments(t9.objectProperty(property.key, value, property.computed), property)
1655
+ );
1656
+ }
1657
+ removeEmptyParents(path) {
1658
+ for (let depth = path.length - 1; depth > 0; depth--) {
1659
+ let ancestor = this.inspect(path.slice(0, depth));
1660
+ if (ancestor.ok === !1 || !t9.isObjectProperty(ancestor.property) || !ancestor.parent)
1661
+ return;
1662
+ let value = this.resolveExpression(ancestor.property.value);
1663
+ if (!t9.isObjectExpression(value) || value.properties.length > 0 || !lookupProperty(ancestor.parent, path[depth - 1], !0).ok)
1664
+ return;
1665
+ ancestor.parent.properties.splice(ancestor.parent.properties.indexOf(ancestor.property), 1);
1666
+ }
1667
+ }
1668
+ normalizePath(path) {
1669
+ if (this.prefix.length === 0)
1670
+ return [...path];
1671
+ if (!(path.length < this.prefix.length || this.prefix.some((part, index) => path[index] !== part)))
1672
+ return path.slice(this.prefix.length);
1673
+ }
1674
+ readValue(node) {
1675
+ let value = this.resolveExpression(node);
1676
+ if (t9.isStringLiteral(value) || t9.isNumericLiteral(value) || t9.isBooleanLiteral(value))
1677
+ return value.value;
1678
+ if (t9.isNullLiteral(value))
1679
+ return null;
1680
+ if (t9.isIdentifier(value))
1681
+ return value.name === "undefined" ? void 0 : UNRESOLVED;
1682
+ if (t9.isTemplateLiteral(value) && value.expressions.length === 0)
1683
+ return value.quasis[0].value.cooked ?? UNRESOLVED;
1684
+ if (t9.isUnaryExpression(value)) {
1685
+ let argument = this.readValue(value.argument);
1686
+ return typeof argument != "number" ? UNRESOLVED : value.operator === "-" ? -argument : value.operator === "+" ? argument : UNRESOLVED;
1687
+ }
1688
+ if (t9.isArrayExpression(value)) {
1689
+ let elements = [];
1690
+ for (let element of value.elements) {
1691
+ if (!element) {
1692
+ elements.length++;
1693
+ continue;
1694
+ }
1695
+ let item = this.readValue(t9.isSpreadElement(element) ? element.argument : element);
1696
+ if (item === UNRESOLVED)
1697
+ return UNRESOLVED;
1698
+ if (t9.isSpreadElement(element)) {
1699
+ if (!Array.isArray(item))
1700
+ return UNRESOLVED;
1701
+ elements.push(...item);
1702
+ } else
1703
+ elements.push(item);
1704
+ }
1705
+ return elements;
1706
+ }
1707
+ if (t9.isObjectExpression(value)) {
1708
+ let entries = [];
1709
+ for (let property of value.properties) {
1710
+ if (t9.isSpreadElement(property)) {
1711
+ let spread = this.readValue(property.argument);
1712
+ if (typeof spread != "object" || spread === null || Array.isArray(spread))
1713
+ return UNRESOLVED;
1714
+ entries.push(...Object.entries(spread));
1715
+ continue;
1716
+ }
1717
+ let key = staticKey(property);
1718
+ if (!t9.isObjectProperty(property) || key === void 0 || key === "__proto__" && !property.computed)
1719
+ return UNRESOLVED;
1720
+ let item = this.readValue(property.value);
1721
+ if (item === UNRESOLVED)
1722
+ return UNRESOLVED;
1723
+ entries.push([key, item]);
1724
+ }
1725
+ return Object.fromEntries(entries);
1726
+ }
1727
+ return UNRESOLVED;
1728
+ }
1729
+ resolveExpression(node) {
1730
+ let program = this.root.scope.getProgramParent().path;
1731
+ if (!program.isProgram())
1732
+ return;
1733
+ let value = unwrapExpression(node), visited = /* @__PURE__ */ new Set();
1734
+ for (; t9.isIdentifier(value) && !visited.has(value); ) {
1735
+ visited.add(value);
1736
+ let reference = pathForNode(program, value), binding = reference?.scope.getBinding(value.name);
1737
+ if (!binding && reference && value.name === "undefined")
1738
+ return value;
1739
+ if (!binding?.constant || binding.referencePaths.length !== 1 || binding.referencePaths[0].node !== value || !binding.path.isVariableDeclarator() || !binding.path.node.init)
1740
+ return;
1741
+ value = unwrapExpression(binding.path.node.init);
1742
+ }
1743
+ return value;
1744
+ }
1745
+ inspect(path) {
1746
+ let object = this.root.node, parent, property;
1747
+ for (let [index, name] of path.entries()) {
1748
+ let lookup = lookupProperty(object, name);
1749
+ if (lookup.ok === !1)
1750
+ return lookup;
1751
+ if (parent = object, property = lookup.property, !property || index === path.length - 1)
1752
+ return { ok: !0, parent, property };
1753
+ if (!t9.isObjectProperty(property))
1754
+ return { ok: !1, code: "unsupported-member", node: property };
1755
+ let value = this.resolveExpression(property.value);
1756
+ if (!t9.isObjectExpression(value))
1757
+ return { ok: !1, code: "unsupported-member", node: property.value };
1758
+ object = value;
1759
+ }
1760
+ return { ok: !0, parent, property };
1761
+ }
1762
+ insert(path, property) {
1763
+ let object = this.root.node;
1764
+ for (let name of path.slice(0, -1)) {
1765
+ let lookup = lookupProperty(object, name);
1766
+ if (lookup.ok === !1)
1767
+ throw this.root.buildCodeFrameError("CsfObject mutation preflight was invalidated");
1768
+ if (lookup.property) {
1769
+ let value = t9.isObjectProperty(lookup.property) ? this.resolveExpression(lookup.property.value) : void 0;
1770
+ if (!t9.isObjectExpression(value))
1771
+ throw this.root.buildCodeFrameError("CsfObject mutation preflight was invalidated");
1772
+ object = value;
1773
+ } else {
1774
+ let child = t9.objectExpression([]);
1775
+ object.properties.push(t9.objectProperty(keyNode(name), child)), object = child;
1776
+ }
1777
+ }
1778
+ object.properties.push(property);
1779
+ }
1780
+ failure(code, path, node, message = `Cannot mutate ${path.join(".")} because the target contains ${code.replaceAll("-", " ")}`) {
1781
+ let diagnostic = {
1782
+ code,
1783
+ target: this.target,
1784
+ path: [...path],
1785
+ message,
1786
+ ...node.loc ? { loc: node.loc } : {}
1787
+ };
1788
+ return this.reportDiagnostic(diagnostic), { ok: !1, changed: !1, diagnostic };
1789
+ }
1790
+ success() {
1791
+ return this.#changed = !0, this.markChanged(), this.root.scope.getProgramParent().crawl(), { ok: !0, changed: !0 };
1792
+ }
1793
+ }, createCsfObject = (target, root, prefix, report, markChanged) => new CsfObjectEditor(target, root, prefix, report, markChanged);
1794
+
1795
+ // src/csf-tools/CsfObjectDiscovery.ts
1796
+ var storyTarget = ({ exportName, localName }) => ({
1797
+ kind: "story",
1798
+ exportName,
1799
+ localName
1800
+ }), reportBindingFailure = (exportName, localName, node, report) => report({
1801
+ code: "ambiguous-binding",
1802
+ target: { kind: "story", exportName, localName },
1803
+ path: [],
1804
+ message: `Cannot mutate ${exportName} because ${localName} is not a unique constant binding`,
1805
+ ...node.loc ? { loc: node.loc } : {}
1806
+ }), addQualifiedBinding = (candidate, exportName, localName, bindings, report, isStory) => {
1807
+ let binding = candidate.scope.getBinding(localName);
1808
+ !binding?.constant || !binding.path.isVariableDeclarator() && !binding.path.isFunctionDeclaration() ? isStory && reportBindingFailure(exportName, localName, candidate.node, report) : bindings.set(`${localName}:${exportName}`, {
1809
+ exportName,
1810
+ localName,
1811
+ declaration: binding.path
1812
+ });
1813
+ }, addDirectBindings = (statement, bindings, report, csf) => {
1814
+ let declaration = statement.get("declaration");
1815
+ if (declaration.isVariableDeclaration())
1816
+ for (let declarator of declaration.get("declarations")) {
1817
+ let id = declarator.get("id");
1818
+ id.isIdentifier() && addQualifiedBinding(
1819
+ id,
1820
+ id.node.name,
1821
+ id.node.name,
1822
+ bindings,
1823
+ report,
1824
+ id.node.name in csf._stories
1825
+ );
1826
+ }
1827
+ else if (declaration.isFunctionDeclaration() && declaration.node.id) {
1828
+ let name = declaration.node.id.name;
1829
+ addQualifiedBinding(declaration, name, name, bindings, report, name in csf._stories);
1830
+ }
1831
+ }, addAliasedBindings = (statement, bindings, report, csf) => {
1832
+ if (statement.node.source) {
1833
+ for (let specifier of statement.get("specifiers")) {
1834
+ if (!specifier.isExportSpecifier() || !t10.isIdentifier(specifier.node.local))
1835
+ continue;
1836
+ let exportName = t10.isIdentifier(specifier.node.exported) ? specifier.node.exported.name : specifier.node.exported.value;
1837
+ exportName !== "default" && exportName in csf._stories && report({
1838
+ code: "unsupported-initializer",
1839
+ target: { kind: "story", exportName, localName: specifier.node.local.name },
1840
+ path: [],
1841
+ message: `Cannot mutate re-exported story ${exportName} automatically`,
1842
+ ...specifier.node.loc ? { loc: specifier.node.loc } : {}
1843
+ });
1844
+ }
1845
+ return;
1846
+ }
1847
+ for (let specifier of statement.get("specifiers")) {
1848
+ if (!specifier.isExportSpecifier() || !t10.isIdentifier(specifier.node.local))
1849
+ continue;
1850
+ let exportName = t10.isIdentifier(specifier.node.exported) ? specifier.node.exported.name : specifier.node.exported.value;
1851
+ if (exportName === "default")
1852
+ continue;
1853
+ let localName = specifier.node.local.name;
1854
+ addQualifiedBinding(
1855
+ specifier,
1856
+ exportName,
1857
+ localName,
1858
+ bindings,
1859
+ report,
1860
+ exportName in csf._stories
1861
+ );
1862
+ }
1863
+ }, factoryMember = (node) => {
1864
+ let unwrapped = node && unwrapExpression(node);
1865
+ if (!unwrapped || !t10.isCallExpression(unwrapped) || !t10.isMemberExpression(unwrapped.callee))
1866
+ return;
1867
+ let property = unwrapped.callee.property;
1868
+ if (!(unwrapped.callee.computed || !t10.isIdentifier(property)))
1869
+ return property.name === "story" || property.name === "extend" ? property.name : void 0;
1870
+ }, storyBindings = (csf, report) => {
1871
+ let bindings = /* @__PURE__ */ new Map();
1872
+ for (let statement of csf._file.path.get("body"))
1873
+ !statement.isExportNamedDeclaration() || statement.node.exportKind === "type" || (addDirectBindings(statement, bindings, report, csf), addAliasedBindings(statement, bindings, report, csf));
1874
+ let candidates = [...bindings.values()].filter((binding) => binding.exportName in csf._stories), unique = /* @__PURE__ */ new Map();
1875
+ for (let candidate of candidates) {
1876
+ let previous = unique.get(candidate.declaration.node);
1877
+ (!previous || !(previous.exportName in csf._stories) && candidate.exportName in csf._stories) && unique.set(candidate.declaration.node, candidate);
1878
+ }
1879
+ return [...unique.values()];
1880
+ }, isFactoryMeta = (csf, name, seen = /* @__PURE__ */ new Set()) => {
1881
+ let binding = csf._file.path.scope.getBinding(name);
1882
+ if (seen.has(name) || !csf._metaFactoryCall || !binding?.constant || !binding.path.isVariableDeclarator() || !t10.isExpression(binding.path.node.init))
1883
+ return !1;
1884
+ seen.add(name);
1885
+ let initializer = withoutTypeCalls(unwrapExpression(binding.path.node.init));
1886
+ return initializer === csf._metaFactoryCall || t10.isIdentifier(initializer) && isFactoryMeta(csf, initializer.name, seen);
1887
+ }, isFactoryStory = (csf, node, seen = /* @__PURE__ */ new Set()) => {
1888
+ if (!isCsfFactoryCall(node))
1889
+ return !1;
1890
+ let receiver = csfFactoryReceiver(node).name;
1891
+ if (node.callee.property.name === "story")
1892
+ return isFactoryMeta(csf, receiver);
1893
+ if (seen.has(receiver))
1894
+ return !1;
1895
+ seen.add(receiver);
1896
+ let binding = csf._file.path.scope.getBinding(receiver), initializer = binding?.constant && binding.path.isVariableDeclarator() ? binding.path.node.init : void 0;
1897
+ return initializer ? isFactoryStory(csf, unwrapExpression(initializer), seen) : !1;
1898
+ }, factoryMetaConfigurationIsSafe = (csf) => {
1899
+ let argument = csf._metaFactoryCall?.arguments[0];
1900
+ if (!argument || !t10.isIdentifier(argument))
1901
+ return !0;
1902
+ let binding = csf._file.path.scope.getBinding(argument.name);
1903
+ if (!binding?.constant || !binding.path.isVariableDeclarator() || !binding.path.parentPath?.isVariableDeclaration({ kind: "const" }))
1904
+ return !1;
1905
+ let initializer = binding.path.node.init;
1906
+ return !initializer || !t10.isObjectExpression(unwrapExpression(initializer)) ? !1 : binding.referencePaths.length === 1 && binding.referencePaths[0].node === argument;
1907
+ }, discoverMeta = (csf, report, markChanged) => {
1908
+ if (csf._metaIsFactory && csf._metaFactoryCall && !factoryMetaConfigurationIsSafe(csf))
1909
+ return report({
1910
+ code: "unsupported-initializer",
1911
+ target: { kind: "meta" },
1912
+ path: [],
1913
+ message: "Cannot mutate CSF factory meta with an identifier-backed configuration",
1914
+ ...csf._metaFactoryCall.loc ? { loc: csf._metaFactoryCall.loc } : {}
1915
+ }), [];
1916
+ let meta = metaObjectPath(csf);
1917
+ if (meta) {
1918
+ let binding = csf._metaVariableName ? meta.scope.getBinding(csf._metaVariableName) : void 0;
1919
+ return binding && !binding.constant ? (report({
1920
+ code: "ambiguous-binding",
1921
+ target: { kind: "meta" },
1922
+ path: [],
1923
+ message: `Cannot mutate meta because ${csf._metaVariableName} is not a unique constant binding`,
1924
+ ...binding.path.node.loc ? { loc: binding.path.node.loc } : {}
1925
+ }), []) : [createCsfObject({ kind: "meta" }, meta, [], report, markChanged)];
1926
+ }
1927
+ return csf._metaIsFactory && csf._metaFactoryCall && report({
1928
+ code: "unsupported-initializer",
1929
+ target: { kind: "meta" },
1930
+ path: [],
1931
+ message: "Cannot mutate CSF factory meta automatically; move the field manually",
1932
+ ...csf._metaFactoryCall.loc ? { loc: csf._metaFactoryCall.loc } : {}
1933
+ }), [];
1934
+ }, discoverStories = (csf, bindings, report, markChanged) => bindings.flatMap((binding) => {
1935
+ let declaration = binding.declaration, init = declaration.isVariableDeclarator() ? declaration.get("init") : declaration, node = init.node ? unwrapExpression(init.node) : void 0;
1936
+ if (node && factoryMember(node)) {
1937
+ let argument = t10.isCallExpression(node) ? node.arguments[0] : void 0, argumentNode = argument && t10.isExpression(argument) ? unwrapExpression(argument) : void 0;
1938
+ if (t10.isCallExpression(node) && isFactoryStory(csf, node) && node.arguments.length === 1 && argumentNode && t10.isObjectExpression(argumentNode)) {
1939
+ let root2 = pathForNode(csf._file.path, argumentNode);
1940
+ return root2 ? [createCsfObject(storyTarget(binding), root2, [], report, markChanged)] : [];
1941
+ }
1942
+ return report({
1943
+ code: "unsupported-initializer",
1944
+ target: storyTarget(binding),
1945
+ path: [],
1946
+ message: `Cannot mutate CSF factory story ${binding.exportName} because its configuration is not an inline object literal`,
1947
+ ...node.loc ? { loc: node.loc } : {}
1948
+ }), [];
1949
+ }
1950
+ let expression = init.isExpression() ? init : void 0, unwrapped = expression && unwrapExpression(expression.node), root = unwrapped && t10.isObjectExpression(unwrapped) ? pathForNode(csf._file.path, unwrapped) : void 0;
1951
+ return root ? [createCsfObject(storyTarget(binding), root, [], report, markChanged)] : [];
1952
+ }), annotationCandidates = (csf, statement, bindings) => {
1953
+ if (!statement.isExpressionStatement())
1954
+ return [];
1955
+ let expression = statement.get("expression");
1956
+ if (!expression.isAssignmentExpression())
1957
+ return [];
1958
+ let left = expression.get("left"), right = expression.get("right");
1959
+ if (!left.isMemberExpression() || !right.isExpression())
1960
+ return [];
1961
+ let object = left.get("object"), property = left.get("property");
1962
+ if (!object.isIdentifier())
1963
+ return [];
1964
+ let propertyName = !left.node.computed && property.isIdentifier() ? property.node.name : left.node.computed && property.isStringLiteral() ? property.node.value : void 0, binding = bindings.get(object.node.name);
1965
+ if (!propertyName && left.node.computed && binding)
1966
+ return [
1967
+ {
1968
+ target: {
1969
+ kind: "story-annotation",
1970
+ exportName: binding.exportName,
1971
+ localName: binding.localName,
1972
+ annotation: "parameters"
1973
+ },
1974
+ annotation: "parameters",
1975
+ node: property.node,
1976
+ message: `Cannot mutate ${binding.localName} annotation because its computed name is not a static string literal`
1977
+ }
1978
+ ];
1979
+ if (!propertyName)
1980
+ return [];
1981
+ let annotation = propertyName === "parameters" || propertyName === "argTypes" ? propertyName : void 0;
1982
+ if (!annotation || !binding)
1983
+ return [];
1984
+ let rootNode = unwrapExpression(right.node);
1985
+ return [
1986
+ {
1987
+ target: {
1988
+ kind: "story-annotation",
1989
+ exportName: binding.exportName,
1990
+ localName: binding.localName,
1991
+ annotation
1992
+ },
1993
+ annotation,
1994
+ root: expression.node.operator === "=" && t10.isObjectExpression(rootNode) ? pathForNode(csf._file.path, rootNode) : void 0,
1995
+ node: right.node,
1996
+ ...expression.node.operator === "=" ? {} : {
1997
+ message: `Cannot mutate ${binding.localName}.${annotation} because it uses ${expression.node.operator} assignment`
1998
+ }
1999
+ }
2000
+ ];
2001
+ }, reportOrCreateAnnotation = (matches, report, markChanged) => {
2002
+ let [candidate] = matches;
2003
+ return matches.length > 1 ? (report({
2004
+ code: "ambiguous-binding",
2005
+ target: candidate.target,
2006
+ path: [candidate.annotation],
2007
+ message: `Cannot mutate repeated ${candidate.target.localName}.${candidate.annotation} assignments`,
2008
+ ...candidate.node.loc ? { loc: candidate.node.loc } : {}
2009
+ }), []) : candidate.root ? [
2010
+ createCsfObject(candidate.target, candidate.root, [candidate.annotation], report, markChanged)
2011
+ ] : (report({
2012
+ code: "unsupported-initializer",
2013
+ target: candidate.target,
2014
+ path: [candidate.annotation],
2015
+ message: candidate.message ?? `Cannot mutate ${candidate.target.localName}.${candidate.annotation} because its value is not an object literal`,
2016
+ ...candidate.node.loc ? { loc: candidate.node.loc } : {}
2017
+ }), []);
2018
+ }, discoverAnnotations = (csf, storyBindings2, report, markChanged) => {
2019
+ let bindings = new Map(storyBindings2.map((binding) => [binding.localName, binding])), candidates = /* @__PURE__ */ new Map();
2020
+ for (let statement of csf._file.path.get("body"))
2021
+ for (let candidate of annotationCandidates(csf, statement, bindings)) {
2022
+ let identity = `${candidate.target.localName}:${candidate.annotation}`;
2023
+ candidates.set(identity, [...candidates.get(identity) ?? [], candidate]);
2024
+ }
2025
+ return [...candidates.values()].flatMap(
2026
+ (matches) => reportOrCreateAnnotation(matches, report, markChanged)
2027
+ );
2028
+ }, discoverCsfObjects = (csf, options, report, markChanged) => {
2029
+ let includeStories = options.stories ?? !0, bindings = includeStories ? storyBindings(csf, report) : [];
2030
+ return [
2031
+ ...options.meta ?? !0 ? discoverMeta(csf, report, markChanged) : [],
2032
+ ...includeStories ? discoverStories(csf, bindings, report, markChanged) : [],
2033
+ ...includeStories ? discoverAnnotations(csf, bindings, report, markChanged) : []
2034
+ ];
2035
+ };
2036
+
2037
+ // src/csf-tools/findVarInitialization.ts
2038
+ import { types as t11 } from "@aussieljk/forkbook/internal/babel";
2039
+ var findVarInitialization = (identifier, program) => {
2040
+ let init = null, declarations = null;
2041
+ return program.body.find((node) => (t11.isVariableDeclaration(node) ? declarations = node.declarations : t11.isExportNamedDeclaration(node) && t11.isVariableDeclaration(node.declaration) && (declarations = node.declaration.declarations), declarations && declarations.find((decl) => t11.isVariableDeclarator(decl) && t11.isIdentifier(decl.id) && decl.id.name === identifier ? (init = decl.init, !0) : !1))), init;
2042
+ };
2043
+
2044
+ // src/csf-tools/CsfFile.ts
2045
+ var mutationStates = /* @__PURE__ */ new WeakMap(), PREVIEW_FILE_REGEX = /\/preview(.(js|jsx|mjs|ts|tsx))?$/, isValidPreviewPath = (filepath) => PREVIEW_FILE_REGEX.test(filepath);
2046
+ function parseIncludeExclude(prop) {
2047
+ if (t12.isArrayExpression(prop))
2048
+ return prop.elements.map((e) => {
2049
+ if (t12.isStringLiteral(e))
2050
+ return e.value;
2051
+ throw new Error(`Expected string literal: ${e}`);
2052
+ });
2053
+ if (t12.isStringLiteral(prop))
2054
+ return new RegExp(prop.value);
2055
+ if (t12.isRegExpLiteral(prop))
2056
+ return new RegExp(prop.pattern, prop.flags);
2057
+ throw new Error(`Unknown include/exclude: ${prop}`);
2058
+ }
2059
+ function parseTags(prop) {
2060
+ if (!t12.isArrayExpression(prop))
2061
+ throw new Error("CSF: Expected tags array");
2062
+ return prop.elements.map((e) => {
2063
+ if (t12.isStringLiteral(e))
2064
+ return e.value;
2065
+ throw new Error("CSF: Expected tag to be string literal");
2066
+ });
2067
+ }
2068
+ function parseTestTags(optionsNode, program) {
2069
+ if (!optionsNode)
2070
+ return [];
2071
+ let node = optionsNode;
2072
+ if (t12.isIdentifier(node) && (node = findVarInitialization(node.name, program)), t12.isObjectExpression(node)) {
2073
+ let tagsProp = node.properties.find(
2074
+ (property) => t12.isObjectProperty(property) && t12.isIdentifier(property.key) && property.key.name === "tags"
2075
+ );
2076
+ if (tagsProp) {
2077
+ let tagsNode = tagsProp.value;
2078
+ return t12.isIdentifier(tagsNode) && (tagsNode = findVarInitialization(tagsNode.name, program)), parseTags(tagsNode);
2079
+ }
2080
+ }
2081
+ return [];
2082
+ }
2083
+ var formatLocation = (node, fileName) => {
2084
+ let loc = "";
2085
+ if (node.loc) {
2086
+ let { line, column } = node.loc?.start || {};
2087
+ loc = `(line ${line}, col ${column})`;
2088
+ }
2089
+ return `${fileName || ""} ${loc}`.trim();
2090
+ }, isModuleMock = (importPath) => MODULE_MOCK_REGEX.test(importPath), isArgsStory = (init, parent, csf) => {
2091
+ let storyFn = init;
2092
+ if (t12.isProgram(parent) && isCanonicalCsf2BindCall(init)) {
2093
+ let boundIdentifier = init.callee.object.name, template = findVarInitialization(boundIdentifier, parent);
2094
+ template && (csf._templates[boundIdentifier] = template, storyFn = template);
2095
+ }
2096
+ return t12.isArrowFunctionExpression(storyFn) || t12.isFunctionDeclaration(storyFn) ? storyFn.params.length > 0 : !1;
2097
+ }, parseExportsOrder = (init) => {
2098
+ if (t12.isArrayExpression(init))
2099
+ return init.elements.map((item) => {
2100
+ if (t12.isStringLiteral(item))
2101
+ return item.value;
2102
+ throw new Error(`Expected string literal named export: ${item}`);
2103
+ });
2104
+ throw new Error(`Expected array of string literals: ${init}`);
2105
+ }, sortExports = (exportByName, order) => order.reduce(
2106
+ (acc, name) => {
2107
+ let namedExport = exportByName[name];
2108
+ return namedExport && (acc[name] = namedExport), acc;
2109
+ },
2110
+ {}
2111
+ ), hasMount = (play) => {
2112
+ if (t12.isArrowFunctionExpression(play) || t12.isFunctionDeclaration(play) || t12.isObjectMethod(play)) {
2113
+ let params = play.params;
2114
+ if (params.length >= 1) {
2115
+ let [arg] = params;
2116
+ if (t12.isObjectPattern(arg))
2117
+ return !!arg.properties.find((prop) => {
2118
+ if (t12.isObjectProperty(prop) && t12.isIdentifier(prop.key))
2119
+ return prop.key.name === "mount";
2120
+ });
2121
+ }
2122
+ }
2123
+ return !1;
2124
+ }, MODULE_MOCK_REGEX = /^[.\/#].*\.mock($|\.[^.]*$)/i, NoMetaError = class extends Error {
2125
+ constructor(message, ast, fileName) {
2126
+ let msg = message.trim();
2127
+ super(dedent`
2128
+ CSF: ${msg} ${formatLocation(ast, fileName)}
2129
+
2130
+ More info: https://storybook.js.org/docs/writing-stories?ref=error#default-export
2131
+ `), this.name = this.constructor.name;
2132
+ }
2133
+ }, MultipleMetaError = class extends Error {
2134
+ constructor(message, ast, fileName) {
2135
+ let msg = `${message} ${formatLocation(ast, fileName)}`.trim();
2136
+ super(dedent`
2137
+ CSF: ${message} ${formatLocation(ast, fileName)}
2138
+
2139
+ More info: https://storybook.js.org/docs/writing-stories?ref=error#default-export
2140
+ `), this.name = this.constructor.name;
2141
+ }
2142
+ }, MixedFactoryError = class extends Error {
2143
+ constructor(message, ast, fileName) {
2144
+ let msg = `${message} ${formatLocation(ast, fileName)}`.trim();
2145
+ super(dedent`
2146
+ CSF: ${message} ${formatLocation(ast, fileName)}
2147
+
2148
+ More info: https://storybook.js.org/docs/writing-stories?ref=error#default-export
2149
+ `), this.name = this.constructor.name;
2150
+ }
2151
+ }, BadMetaError = class extends Error {
2152
+ constructor(message, ast, fileName) {
2153
+ let msg = "".trim();
2154
+ super(dedent`
2155
+ CSF: ${message} ${formatLocation(ast, fileName)}
2156
+
2157
+ More info: https://storybook.js.org/docs/writing-stories?ref=error#default-export
2158
+ `), this.name = this.constructor.name;
2159
+ }
2160
+ }, CsfFile = class {
2161
+ constructor(ast, options, file) {
2162
+ this._stories = {};
2163
+ this._metaAnnotations = {};
2164
+ this._storyExports = {};
2165
+ this._storyDeclarationPath = {};
2166
+ this._storyPaths = {};
2167
+ this._storyStatements = {};
2168
+ this._storyAnnotations = {};
2169
+ this._templates = {};
2170
+ this._tests = [];
2171
+ this._ast = ast, this._file = file, this._options = options, this.imports = [], mutationStates.set(this, { diagnostics: [], changed: !1 });
2172
+ }
2173
+ /**
2174
+ * Read diagnostics from object discovery, reads, and mutations. Check them before writing
2175
+ * because a file can contain both successful edits and unsupported targets.
2176
+ *
2177
+ * @example
2178
+ * ```ts
2179
+ * const [story] = csf.objects({ meta: false });
2180
+ * story.set(['args', 'old'], 1);
2181
+ * story.set(['args', 'current'], 2);
2182
+ * story.rename(['args', 'old'], 'current');
2183
+ * csf.mutationDiagnostics.map(({ code }) => code); // ['occupied-destination']
2184
+ * ```
2185
+ */
2186
+ get mutationDiagnostics() {
2187
+ return [...mutationStates.get(this).diagnostics];
2188
+ }
2189
+ /**
2190
+ * Report whether any object editor has changed this story file.
2191
+ *
2192
+ * @example
2193
+ * ```ts
2194
+ * csf.changed; // false, before any edits
2195
+ * const [story] = csf.objects({ meta: false });
2196
+ * story.set(['args', 'disabled'], true);
2197
+ * csf.changed; // true
2198
+ * ```
2199
+ */
2200
+ get changed() {
2201
+ return mutationStates.get(this).changed;
2202
+ }
2203
+ /**
2204
+ * Discover editors for the meta and stories, including CSF2 parameter and argTypes assignments. Unsupported
2205
+ * targets are skipped and reported in `mutationDiagnostics`.
2206
+ *
2207
+ * @example
2208
+ * ```ts
2209
+ * const csf = loadCsf('export default {}; export const Primary = {};', {
2210
+ * makeTitle: () => 'Example',
2211
+ * }).parse();
2212
+ * const [story] = csf.objects({ meta: false });
2213
+ * story.set(['args', 'disabled'], true);
2214
+ * story.getValue(['args']); // { disabled: true }
2215
+ * csf.changed; // true
2216
+ * ```
2217
+ */
2218
+ objects(options = {}) {
2219
+ let state = mutationStates.get(this);
2220
+ return discoverCsfObjects(
2221
+ this,
2222
+ options,
2223
+ (diagnostic) => state.diagnostics.push(diagnostic),
2224
+ () => {
2225
+ state.changed = !0;
2226
+ }
2227
+ );
2228
+ }
2229
+ _parseTitle(value) {
2230
+ let node = t12.isIdentifier(value) ? findVarInitialization(value.name, this._ast.program) : value;
2231
+ if (t12.isStringLiteral(node))
2232
+ return node.value;
2233
+ if (t12.isTSSatisfiesExpression(node) && t12.isStringLiteral(node.expression))
2234
+ return node.expression.value;
2235
+ throw new Error(dedent`
2236
+ CSF: unexpected dynamic title ${formatLocation(node, this._options.fileName)}
2237
+
2238
+ More info: https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#string-literal-titles
2239
+ `);
2240
+ }
2241
+ _parseMeta(declaration, program) {
2242
+ if (this._metaNode)
2243
+ throw new MultipleMetaError("multiple meta objects", declaration, this._options.fileName);
2244
+ this._metaNode = declaration;
2245
+ let meta = {};
2246
+ declaration.properties.forEach((p) => {
2247
+ if (t12.isIdentifier(p.key)) {
2248
+ let value = t12.isObjectMethod(p) ? p : p.value;
2249
+ if (this._metaAnnotations[p.key.name] = value, p.key.name === "title")
2250
+ meta.title = this._parseTitle(p.value);
2251
+ else if (["includeStories", "excludeStories"].includes(p.key.name))
2252
+ meta[p.key.name] = parseIncludeExclude(p.value);
2253
+ else if (p.key.name === "component") {
2254
+ let n = p.value;
2255
+ if (t12.isIdentifier(n)) {
2256
+ let id = n.name, importStmt = program.body.find(
2257
+ (stmt) => t12.isImportDeclaration(stmt) && stmt.specifiers.find((spec) => spec.local.name === id)
2258
+ );
2259
+ if (importStmt) {
2260
+ let { source } = importStmt, specifier = importStmt.specifiers.find((spec) => spec.local.name === id);
2261
+ t12.isStringLiteral(source) && specifier && (this._rawComponentPath = source.value, (t12.isImportSpecifier(specifier) || t12.isImportDefaultSpecifier(specifier)) && (this._componentImportSpecifier = specifier));
2262
+ }
2263
+ }
2264
+ let { code } = recast.print(p.value, {});
2265
+ meta.component = code;
2266
+ } else if (p.key.name === "tags") {
2267
+ let node = p.value;
2268
+ t12.isIdentifier(node) && (node = findVarInitialization(node.name, this._ast.program)), meta.tags = parseTags(node);
2269
+ } else if (p.key.name === "id")
2270
+ if (t12.isStringLiteral(p.value))
2271
+ meta.id = p.value.value;
2272
+ else
2273
+ throw new Error(`Unexpected component id: ${p.value}`);
2274
+ }
2275
+ }), this._meta = meta;
2276
+ }
2277
+ getStoryExport(key) {
2278
+ let node = this._storyExports[key];
2279
+ return node = t12.isVariableDeclarator(node) ? node.init : node, isCanonicalCsf2BindCall(node) && (node = this._templates[node.callee.object.name]), node;
2280
+ }
2281
+ parse() {
2282
+ let self = this;
2283
+ if (traverse2(this._ast, {
2284
+ ExportDefaultDeclaration: {
2285
+ enter(path) {
2286
+ let { node, parent } = path, isVariableReference = t12.isIdentifier(node.declaration) && t12.isProgram(parent);
2287
+ if (self._options.transformInlineMeta && !isVariableReference && t12.isExpression(node.declaration)) {
2288
+ let metaId = path.scope.generateUidIdentifier("meta");
2289
+ self._metaVariableName = metaId.name;
2290
+ let nodes = [
2291
+ t12.variableDeclaration("const", [t12.variableDeclarator(metaId, node.declaration)]),
2292
+ t12.exportDefaultDeclaration(metaId)
2293
+ ];
2294
+ nodes.forEach((_node) => _node.loc = path.node.loc), path.replaceWithMultiple(nodes);
2295
+ return;
2296
+ }
2297
+ let metaNode, decl;
2298
+ if (isVariableReference) {
2299
+ let variableName = node.declaration.name;
2300
+ self._metaVariableName = variableName;
2301
+ let isMetaVariable = (declaration) => t12.isIdentifier(declaration.id) && declaration.id.name === variableName;
2302
+ self._metaStatementPath = self._file.path.get("body").find(
2303
+ (path2) => path2.isVariableDeclaration() && path2.node.declarations.some(isMetaVariable)
2304
+ ), self._metaStatement = self._metaStatementPath?.node, decl = (self?._metaStatement?.declarations || []).find(
2305
+ isMetaVariable
2306
+ )?.init;
2307
+ } else
2308
+ self._metaStatement = node, self._metaStatementPath = path, decl = node.declaration;
2309
+ if (t12.isObjectExpression(decl) ? metaNode = decl : /* export default { ... } as Meta<...> */ /* export default { ... } satisfies Meta<...> */ (t12.isTSAsExpression(decl) || t12.isTSSatisfiesExpression(decl)) && t12.isObjectExpression(decl.expression) ? metaNode = decl.expression : (
2310
+ // export default { ... } satisfies Meta as Meta<...>
2311
+ t12.isTSAsExpression(decl) && t12.isTSSatisfiesExpression(decl.expression) && t12.isObjectExpression(decl.expression.expression) && (metaNode = decl.expression.expression)
2312
+ ), metaNode && t12.isProgram(parent) && self._parseMeta(metaNode, parent), self._metaStatement && !self._metaNode)
2313
+ throw new NoMetaError(
2314
+ "default export must be an object",
2315
+ self._metaStatement,
2316
+ self._options.fileName
2317
+ );
2318
+ self._metaPath = path;
2319
+ }
2320
+ },
2321
+ ExportNamedDeclaration: {
2322
+ enter(path) {
2323
+ let { node, parent } = path, declaration = path.get("declaration"), declarations;
2324
+ declaration.isVariableDeclaration() ? declarations = declaration.get("declarations").filter((d) => d.isVariableDeclarator()) : declaration.isFunctionDeclaration() && (declarations = [declaration]), declarations ? declarations.forEach((declPath) => {
2325
+ let decl = declPath.node, id = declPath.node.id;
2326
+ if (t12.isIdentifier(id)) {
2327
+ let { name: exportName } = id;
2328
+ if (exportName === "__namedExportsOrder" && declPath.isVariableDeclarator()) {
2329
+ self._namedExportsOrder = parseExportsOrder(declPath.node.init);
2330
+ return;
2331
+ }
2332
+ let storyNode;
2333
+ t12.isVariableDeclarator(decl) ? t12.isTSAsExpression(decl.init) && t12.isTSSatisfiesExpression(decl.init.expression) ? storyNode = decl.init.expression.expression : t12.isTSAsExpression(decl.init) || t12.isTSSatisfiesExpression(decl.init) ? storyNode = decl.init.expression : storyNode = decl.init : storyNode = decl;
2334
+ let storyIsFactory = !1;
2335
+ if (storyNode && isCsfFactoryCall(storyNode) && (storyIsFactory = !0, storyNode = storyNode.arguments[0]), self._metaIsFactory && !storyIsFactory)
2336
+ return;
2337
+ if (!self._metaIsFactory && storyIsFactory)
2338
+ throw self._metaNode ? new MixedFactoryError(
2339
+ "expected non-factory story",
2340
+ storyNode,
2341
+ self._options.fileName
2342
+ ) : new BadMetaError(
2343
+ "meta() factory must be imported from .forkbook/preview configuration",
2344
+ storyNode,
2345
+ self._options.fileName
2346
+ );
2347
+ self._storyExports[exportName] = decl, self._storyDeclarationPath[exportName] = declPath, self._storyPaths[exportName] = path, self._storyStatements[exportName] = node;
2348
+ let name = storyNameFromExport(exportName);
2349
+ self._storyAnnotations[exportName] ? logger.warn(
2350
+ `Unexpected annotations for "${exportName}" before story declaration`
2351
+ ) : self._storyAnnotations[exportName] = {};
2352
+ let parameters = {};
2353
+ t12.isObjectExpression(storyNode) ? (parameters.__isArgsStory = !0, storyNode.properties.forEach((p) => {
2354
+ if (t12.isIdentifier(p.key)) {
2355
+ let key = p.key.name;
2356
+ if (t12.isObjectMethod(p))
2357
+ self._storyAnnotations[exportName][key] = p;
2358
+ else {
2359
+ if (p.key.name === "render")
2360
+ parameters.__isArgsStory = isArgsStory(
2361
+ p.value,
2362
+ parent,
2363
+ self
2364
+ );
2365
+ else if (p.key.name === "name" && t12.isStringLiteral(p.value))
2366
+ name = p.value.value;
2367
+ else if (p.key.name === "storyName" && t12.isStringLiteral(p.value))
2368
+ logger.warn(
2369
+ `Unexpected usage of "storyName" in "${exportName}". Please use "name" instead.`
2370
+ );
2371
+ else if (p.key.name === "parameters" && t12.isObjectExpression(p.value)) {
2372
+ let idProperty = p.value.properties.find(
2373
+ (property) => t12.isObjectProperty(property) && t12.isIdentifier(property.key) && property.key.name === "__id"
2374
+ );
2375
+ idProperty && (parameters.__id = idProperty.value.value);
2376
+ }
2377
+ self._storyAnnotations[exportName][p.key.name] = p.value;
2378
+ }
2379
+ }
2380
+ })) : parameters.__isArgsStory = isArgsStory(storyNode, parent, self), self._stories[exportName] = {
2381
+ id: "FIXME",
2382
+ name,
2383
+ parameters,
2384
+ __stats: {
2385
+ factory: storyIsFactory
2386
+ }
2387
+ };
2388
+ }
2389
+ }) : node.specifiers.length > 0 && node.specifiers.forEach((specifier) => {
2390
+ if (t12.isExportSpecifier(specifier) && (t12.isIdentifier(specifier.exported) || t12.isStringLiteral(specifier.exported))) {
2391
+ let exportName = t12.isIdentifier(specifier.exported) ? specifier.exported.name : specifier.exported.value, { name: localName } = specifier.local, decl = t12.isProgram(parent) ? findVarInitialization(localName, parent) : specifier.local;
2392
+ if (exportName === "default") {
2393
+ self._metaVariableName = localName;
2394
+ let metaNode;
2395
+ t12.isObjectExpression(decl) ? metaNode = decl : /* export default { ... } as Meta<...> */ /* export default { ... } satisfies Meta<...> */ (t12.isTSAsExpression(decl) || t12.isTSSatisfiesExpression(decl)) && t12.isObjectExpression(decl.expression) ? metaNode = decl.expression : (
2396
+ // export default { ... } satisfies Meta as Meta<...>
2397
+ t12.isTSAsExpression(decl) && t12.isTSSatisfiesExpression(decl.expression) && t12.isObjectExpression(decl.expression.expression) && (metaNode = decl.expression.expression)
2398
+ ), metaNode && t12.isProgram(parent) && self._parseMeta(metaNode, parent);
2399
+ } else {
2400
+ let annotations = {}, storyNode = decl;
2401
+ t12.isObjectExpression(storyNode) && storyNode.properties.forEach((p) => {
2402
+ t12.isIdentifier(p.key) && (annotations[p.key.name] = p.value);
2403
+ }), self._storyAnnotations[exportName] = annotations, self._storyStatements[exportName] = decl, self._storyPaths[exportName] = path, self._stories[exportName] = {
2404
+ id: "FIXME",
2405
+ name: exportName,
2406
+ localName,
2407
+ parameters: {},
2408
+ __stats: {}
2409
+ };
2410
+ }
2411
+ }
2412
+ });
2413
+ }
2414
+ },
2415
+ ExpressionStatement: {
2416
+ enter({ node, parent }) {
2417
+ let { expression } = node;
2418
+ if (t12.isProgram(parent) && t12.isAssignmentExpression(expression) && t12.isMemberExpression(expression.left) && t12.isIdentifier(expression.left.object) && t12.isIdentifier(expression.left.property)) {
2419
+ let exportName = expression.left.object.name, annotationKey = expression.left.property.name, annotationValue = expression.right;
2420
+ if (self._storyAnnotations[exportName] && (self._storyAnnotations[exportName][annotationKey] = annotationValue), annotationKey === "storyName" && t12.isStringLiteral(annotationValue)) {
2421
+ let storyName = annotationValue.value, story = self._stories[exportName];
2422
+ if (!story)
2423
+ return;
2424
+ story.name = storyName;
2425
+ }
2426
+ }
2427
+ if (t12.isCallExpression(expression) && t12.isMemberExpression(expression.callee) && t12.isIdentifier(expression.callee.object) && t12.isIdentifier(expression.callee.property) && expression.callee.property.name === "test" && expression.arguments.length >= 2 && t12.isStringLiteral(expression.arguments[0])) {
2428
+ let exportName = expression.callee.object.name, testName = expression.arguments[0].value, testFunction = expression.arguments.length === 2 ? expression.arguments[1] : expression.arguments[2], testArguments = expression.arguments.length === 2 ? null : expression.arguments[1], tags = parseTestTags(testArguments, self._ast.program);
2429
+ self._tests.push({
2430
+ function: testFunction,
2431
+ name: testName,
2432
+ node: expression,
2433
+ // can't set id because meta title isn't available yet
2434
+ // so it's set later on
2435
+ id: "FIXME",
2436
+ tags,
2437
+ parent: { node: self._storyStatements[exportName] }
2438
+ }), self._stories[exportName].__stats.tests = !0;
2439
+ }
2440
+ }
2441
+ },
2442
+ CallExpression: {
2443
+ enter(path) {
2444
+ let { node } = path, { callee } = node;
2445
+ if (t12.isIdentifier(callee) && callee.name === "storiesOf")
2446
+ throw new Error(dedent`
2447
+ Unexpected \`storiesOf\` usage: ${formatLocation(node, self._options.fileName)}.
2448
+
2449
+ \`storiesOf\` was removed in Forkbook 8.0. Write stories in CSF instead.
2450
+ `);
2451
+ if (t12.isMemberExpression(callee) && t12.isIdentifier(callee.property) && callee.property.name === "meta" && !callee.computed) {
2452
+ let rootObject = callee.object;
2453
+ if (t12.isCallExpression(rootObject) && t12.isMemberExpression(rootObject.callee) && (rootObject = rootObject.callee.object), t12.isIdentifier(rootObject)) {
2454
+ let configParent = path.scope.getBinding(rootObject.name)?.path?.parentPath?.node;
2455
+ if (t12.isImportDeclaration(configParent)) {
2456
+ if (isValidPreviewPath(configParent.source.value)) {
2457
+ self._metaIsFactory = !0, self._metaFactoryCall = node;
2458
+ let metaDeclarator = path.findParent((p) => p.isVariableDeclarator());
2459
+ self._metaVariableName = metaDeclarator?.isVariableDeclarator() && t12.isIdentifier(metaDeclarator.node.id) ? metaDeclarator.node.id.name : callee.property.name;
2460
+ let [argument] = node.arguments, argumentBinding = argument && t12.isIdentifier(argument) ? path.scope.getBinding(argument.name) : void 0, argumentNode = argumentBinding?.constant && argumentBinding.path.isVariableDeclarator() ? argumentBinding.path.node.init : argument, unwrappedArgument = argumentNode && unwrapExpression(argumentNode);
2461
+ t12.isObjectExpression(unwrappedArgument) ? self._parseMeta(unwrappedArgument, self._ast.program) : (self._metaNodeIsSynthetic = !0, self._parseMeta(t12.objectExpression([]), self._ast.program));
2462
+ } else if (rootObject.name === "preview")
2463
+ throw new BadMetaError(
2464
+ "meta() factory must be imported from .forkbook/preview configuration",
2465
+ configParent,
2466
+ self._options.fileName
2467
+ );
2468
+ }
2469
+ }
2470
+ }
2471
+ }
2472
+ },
2473
+ ImportDeclaration: {
2474
+ enter({ node }) {
2475
+ let { source } = node;
2476
+ if (t12.isStringLiteral(source))
2477
+ self.imports.push(source.value);
2478
+ else
2479
+ throw new Error("CSF: unexpected import source");
2480
+ }
2481
+ }
2482
+ }), !self._meta)
2483
+ throw new NoMetaError("missing default export", self._ast, self._options.fileName);
2484
+ let entries = Object.entries(self._stories);
2485
+ if (self._meta.title = this._options.makeTitle(self._meta?.title), self._metaAnnotations.play && (self._meta.tags = [...self._meta.tags || [], Tag.PLAY_FN]), self._stories = entries.reduce(
2486
+ (acc, [key, story]) => {
2487
+ if (!isExportStory(key, self._meta))
2488
+ return acc;
2489
+ let id = story.parameters?.__id ?? toId(self._meta?.id || self._meta?.title, storyNameFromExport(key)), parameters = { ...story.parameters, __id: id }, { includeStories } = self._meta || {};
2490
+ key === "__page" && (entries.length === 1 || Array.isArray(includeStories) && includeStories.length === 1) && (parameters.docsOnly = !0), acc[key] = { ...story, id, parameters };
2491
+ let storyAnnotations = self._storyAnnotations[key], { tags, play } = storyAnnotations;
2492
+ if (tags) {
2493
+ let node = t12.isIdentifier(tags) ? findVarInitialization(tags.name, this._ast.program) : tags;
2494
+ acc[key].tags = parseTags(node);
2495
+ }
2496
+ play && (acc[key].tags = [...acc[key].tags || [], Tag.PLAY_FN]);
2497
+ let stats = acc[key].__stats;
2498
+ ["play", "render", "loaders", "beforeEach", "globals", "tags"].forEach((annotation) => {
2499
+ stats[annotation] = !!storyAnnotations[annotation] || !!self._metaAnnotations[annotation];
2500
+ });
2501
+ let storyExport = self.getStoryExport(key);
2502
+ stats.storyFn = !!(t12.isArrowFunctionExpression(storyExport) || t12.isFunctionDeclaration(storyExport)), stats.mount = hasMount(storyAnnotations.play ?? self._metaAnnotations.play), stats.moduleMock = !!self.imports.find((fname) => isModuleMock(fname));
2503
+ let storyNode = self._storyStatements[key], storyTests = self._tests.filter((t13) => t13.parent.node === storyNode);
2504
+ return storyTests.length > 0 && (stats.tests = !0, storyTests.forEach((test) => {
2505
+ test.id = toTestId(id, test.name);
2506
+ })), acc;
2507
+ },
2508
+ {}
2509
+ ), Object.keys(self._storyExports).forEach((key) => {
2510
+ isExportStory(key, self._meta) || (delete self._storyExports[key], delete self._storyAnnotations[key], delete self._storyStatements[key]);
2511
+ }), self._namedExportsOrder) {
2512
+ let unsortedExports = Object.keys(self._storyExports);
2513
+ self._storyExports = sortExports(self._storyExports, self._namedExportsOrder), self._stories = sortExports(self._stories, self._namedExportsOrder);
2514
+ let sortedExports = Object.keys(self._storyExports);
2515
+ if (unsortedExports.length !== sortedExports.length)
2516
+ throw new Error(
2517
+ `Missing exports after sort: ${unsortedExports.filter(
2518
+ (key) => !sortedExports.includes(key)
2519
+ )}`
2520
+ );
2521
+ }
2522
+ return self;
2523
+ }
2524
+ get meta() {
2525
+ return this._meta;
2526
+ }
2527
+ get stories() {
2528
+ return Object.values(this._stories);
2529
+ }
2530
+ getStoryTests(story) {
2531
+ let storyNode = typeof story == "string" ? this._storyStatements[story] : story;
2532
+ return storyNode ? this._tests.filter((t13) => t13.parent.node === storyNode) : [];
2533
+ }
2534
+ get indexInputs() {
2535
+ let { fileName } = this._options;
2536
+ if (!fileName)
2537
+ throw new Error(
2538
+ dedent`Cannot automatically create index inputs with CsfFile.indexInputs because the CsfFile instance was created without a the fileName option.
2539
+ Either add the fileName option when creating the CsfFile instance, or create the index inputs manually.`
2540
+ );
2541
+ let index = [];
2542
+ return Object.entries(this._stories).map(([exportName, story]) => {
2543
+ let tags = [...this._meta?.tags ?? [], ...story.tags ?? []], storyInput = {
2544
+ rawComponentPath: this._rawComponentPath,
2545
+ exportName,
2546
+ title: this.meta?.title,
2547
+ metaId: this.meta?.id,
2548
+ tags,
2549
+ __id: story.id,
2550
+ __stats: story.__stats
2551
+ }, tests = this.getStoryTests(exportName), hasTests = tests.length > 0;
2552
+ index.push({
2553
+ ...storyInput,
2554
+ type: "story",
2555
+ subtype: "story",
2556
+ name: story.name
2557
+ }), hasTests && tests.forEach((test) => {
2558
+ index.push({
2559
+ ...storyInput,
2560
+ // TODO implementent proper title => path behavior in `transformStoryIndexToStoriesHash`
2561
+ // title: `${storyInput.title}/${story.name}`,
2562
+ type: "story",
2563
+ subtype: "test",
2564
+ name: test.name,
2565
+ parent: story.id,
2566
+ parentName: story.name,
2567
+ tags: [
2568
+ ...storyInput.tags,
2569
+ // this tag comes before test tags so users can invert if they like
2570
+ `!${Tag.AUTODOCS}`,
2571
+ ...test.tags,
2572
+ // this tag comes after test tags so users can't change it
2573
+ Tag.TEST_FN
2574
+ ],
2575
+ __id: test.id
2576
+ });
2577
+ });
2578
+ }), index;
2579
+ }
2580
+ }, babelParseFile = ({
2581
+ code,
2582
+ filename = "",
2583
+ ast
2584
+ }) => new BabelFileClass(
2585
+ { filename, highlightCode: !1 },
2586
+ { code, ast: ast ?? babelParse2(code) }
2587
+ ), loadCsf = (code, options) => {
2588
+ let ast = babelParse2(code), file = babelParseFile({ code, filename: options.fileName, ast });
2589
+ return new CsfFile(ast, options, file);
2590
+ }, formatCsf = (csf, options = { sourceMaps: !1 }, code) => {
2591
+ let result = generate3(csf._ast, options, code);
2592
+ return options.sourceMaps ? result : result.code;
2593
+ }, printCsf = (csf, options = {}) => recast.print(csf._ast, {
2594
+ // Recast defaults this to `os.EOL`, which would carriage-return printed files on Windows.
2595
+ lineTerminator: `
2596
+ `,
2597
+ ...options
2598
+ }), readCsf = async (fileName, options) => {
2599
+ let code = (await readFile(fileName, "utf-8")).toString();
2600
+ return loadCsf(code, { ...options, fileName });
2601
+ }, writeCsf = async (csf, fileName) => {
2602
+ if (!(fileName || csf._options.fileName))
2603
+ throw new Error("Please specify a fileName for writeCsf");
2604
+ await writeFile(fileName, printCsf(csf).code);
2605
+ };
2606
+
2607
+ // src/csf-tools/story-shape/reference-context.ts
2608
+ function createStoryReferenceResolver(options = {}) {
2609
+ let resolver = createModuleResolver({
2610
+ extensions: [...options.extensions ?? [], ...jsTsSourceExtensions],
2611
+ mainFields: ["module", "main"],
2612
+ tsconfig: "auto"
2613
+ });
2614
+ return function() {
2615
+ let parsed = /* @__PURE__ */ new Map();
2616
+ return {
2617
+ externalize: options.externalize ?? selfContained,
2618
+ resolveModule: (fromFile, specifier) => {
2619
+ let filePath;
2620
+ try {
2621
+ filePath = resolver.resolveFileSync(fromFile, specifier);
2622
+ } catch {
2623
+ return;
2624
+ }
2625
+ return parsed.has(filePath) || parsed.set(filePath, parseReferenceModule(filePath)), parsed.get(filePath);
2626
+ }
2627
+ };
2628
+ };
2629
+ }
2630
+ var parseReferenceModule = (filePath) => {
2631
+ try {
2632
+ let code = readFileSync(filePath, "utf8");
2633
+ return { program: babelParseFile({ code, filename: filePath }).path, filePath };
2634
+ } catch {
2635
+ return;
2636
+ }
2637
+ }, selfContained = (node) => isSelfContained(node) ? node : void 0;
2638
+
2639
+ export {
2640
+ defaultResolveConditionNames,
2641
+ createModuleResolver,
2642
+ isTypeSpecifier,
2643
+ importedName,
2644
+ collectImportBindings,
2645
+ resolveComponentImport,
2646
+ buildImportStatements,
2647
+ unwrapExpression,
2648
+ isCanonicalCsf2BindCall,
2649
+ withoutTypeCalls,
2650
+ isCsfFactoryCall,
2651
+ csfFactoryReceiver,
2652
+ templateParts,
2653
+ keyOf,
2654
+ propertyValue,
2655
+ returnedExpression,
2656
+ returnedExpressionPath,
2657
+ resolveReturnedObjectExpression,
2658
+ resolveIdentifierInit,
2659
+ pathForNode,
2660
+ metaObjectPath,
2661
+ sourceOf,
2662
+ resolveObjectMembers,
2663
+ resolveArgsRecord,
2664
+ resolveBindingMembers,
2665
+ resolveReferencedValue,
2666
+ resolveArgValue,
2667
+ isSelfContained,
2668
+ authoredSource,
2669
+ enrichCsfStory,
2670
+ enrichCsfMeta,
2671
+ enrichCsf,
2672
+ extractSource,
2673
+ extractDescription,
2674
+ extractJSDocInfo,
2675
+ extractComponentDescription,
2676
+ jsDocTagsForPath,
2677
+ extractStoryJSDocInfo,
2678
+ normalizeStoryDeclaration,
2679
+ createStoryArgsResolver,
2680
+ unresolvedWarning,
2681
+ noSnippetWarning,
2682
+ resolveRenderFunction,
2683
+ resolveEffectiveRender,
2684
+ createCsfObject,
2685
+ isValidPreviewPath,
2686
+ isModuleMock,
2687
+ NoMetaError,
2688
+ MultipleMetaError,
2689
+ MixedFactoryError,
2690
+ BadMetaError,
2691
+ CsfFile,
2692
+ babelParseFile,
2693
+ loadCsf,
2694
+ formatCsf,
2695
+ printCsf,
2696
+ readCsf,
2697
+ writeCsf,
2698
+ createStoryReferenceResolver,
2699
+ parseReferenceModule
2700
+ };