@vfrey/vfrey 0.0.1 → 1.0.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (603) hide show
  1. package/LICENSE +33 -0
  2. package/README.md +78 -3
  3. package/accounts.example.json +61 -0
  4. package/accounts.first-run.json +41 -0
  5. package/bin/vfrey.mjs +36 -0
  6. package/integration-tools/README.md +43 -0
  7. package/integration-tools/image/pillow.md +32 -0
  8. package/integration-tools/image/playwright.md +33 -0
  9. package/integration-tools/image/resvg.md +36 -0
  10. package/integration-tools/image/satori.md +36 -0
  11. package/integration-tools/image/sharp.md +38 -0
  12. package/integration-tools/video/blender.md +34 -0
  13. package/integration-tools/video/ffmpeg.md +41 -0
  14. package/integration-tools/video/manim.md +37 -0
  15. package/integration-tools/video/motion-canvas.md +37 -0
  16. package/integration-tools/video/remotion.md +50 -0
  17. package/integration-tools/video/revideo.md +32 -0
  18. package/package.json +74 -6
  19. package/skills/vfrey-orchestrator/SKILL.md +15 -0
  20. package/skills/vfrey-orchestrator/channel-video/SKILL.md +41 -0
  21. package/skills/vfrey-product/SKILL.md +63 -0
  22. package/skills/vfrey-product/examples/concurrency-vs-parallelism/framey/cook-one.svg +14 -0
  23. package/skills/vfrey-product/examples/concurrency-vs-parallelism/framey/cook-two.svg +22 -0
  24. package/skills/vfrey-product/examples/concurrency-vs-parallelism/framey/index.html +70 -0
  25. package/skills/vfrey-product/examples/concurrency-vs-parallelism/remotion/cook-one.svg +14 -0
  26. package/skills/vfrey-product/examples/concurrency-vs-parallelism/remotion/cook-two.svg +22 -0
  27. package/skills/vfrey-product/examples/concurrency-vs-parallelism/remotion/index.tsx +49 -0
  28. package/skills/vfrey-product/examples/concurrency-vs-parallelism/script.json +15 -0
  29. package/skills/vfrey-product/examples/octopus-facts/index.html +60 -0
  30. package/skills/vfrey-product/examples/octopus-facts/octopus.svg +8 -0
  31. package/skills/vfrey-product/examples/octopus-facts/script.json +14 -0
  32. package/skills/vfrey-product/push/SKILL.md +15 -0
  33. package/skills/vfrey-product/scenes/NOTICE +5 -0
  34. package/skills/vfrey-product/scenes/blocks.md +57 -0
  35. package/skills/vfrey-product/scenes/craft.md +118 -0
  36. package/skills/vfrey-product/scenes/motion.md +88 -0
  37. package/src/analytics/dashboard.ts +109 -0
  38. package/src/analytics/index.ts +260 -0
  39. package/src/api/client.ts +282 -0
  40. package/src/api/commands.ts +330 -0
  41. package/src/api/config.ts +34 -0
  42. package/src/api/creators.ts +463 -0
  43. package/src/api/credentials.ts +152 -0
  44. package/src/api/mail.ts +333 -0
  45. package/src/api/topics.ts +207 -0
  46. package/src/api/types.ts +205 -0
  47. package/src/cli.ts +467 -0
  48. package/src/cloud/executor.ts +281 -0
  49. package/src/cloud/job.ts +106 -0
  50. package/src/cloud/render-job.ts +187 -0
  51. package/src/config.ts +309 -0
  52. package/src/dashboard-link.ts +180 -0
  53. package/src/dashboard-start.ts +103 -0
  54. package/src/desk/channel.ts +64 -0
  55. package/src/desk/cli.ts +216 -0
  56. package/src/desk/creators-route.ts +129 -0
  57. package/src/desk/fonts/JetBrainsMono-OFL.txt +93 -0
  58. package/src/desk/fonts/google-sans-flex-latin.woff2 +0 -0
  59. package/src/desk/fonts/jetbrains-mono-medium.woff2 +0 -0
  60. package/src/desk/http.ts +460 -0
  61. package/src/desk/mail-route.ts +103 -0
  62. package/src/desk/overlay.ts +112 -0
  63. package/src/desk/preview.ts +422 -0
  64. package/src/desk/screens.ts +149 -0
  65. package/src/desk/secrets.ts +143 -0
  66. package/src/desk/series.ts +127 -0
  67. package/src/desk/state.ts +77 -0
  68. package/src/desk/studio-route.ts +119 -0
  69. package/src/desk/tick-runner.ts +66 -0
  70. package/src/desk/tick.ts +56 -0
  71. package/src/desk/topics-route.ts +41 -0
  72. package/src/desk/ui/app.css +505 -0
  73. package/src/desk/ui/app.js +185 -0
  74. package/src/desk/ui/apple-icon.png +0 -0
  75. package/src/desk/ui/components.js +79 -0
  76. package/src/desk/ui/core.js +156 -0
  77. package/src/desk/ui/favicon.ico +0 -0
  78. package/src/desk/ui/icon.svg +1 -0
  79. package/src/desk/ui/icons.js +49 -0
  80. package/src/desk/ui/index.html +41 -0
  81. package/src/desk/ui/metrics-math.d.ts +22 -0
  82. package/src/desk/ui/metrics-math.js +135 -0
  83. package/src/desk/ui/theme.js +5 -0
  84. package/src/desk/ui/views-creators.js +209 -0
  85. package/src/desk/ui/views-keys.js +114 -0
  86. package/src/desk/ui/views-mail.js +188 -0
  87. package/src/desk/ui/views-misc.js +123 -0
  88. package/src/desk/ui/views-review.js +119 -0
  89. package/src/desk/ui/views-runs.js +350 -0
  90. package/src/desk/ui/views-screens.js +163 -0
  91. package/src/desk/ui/views-series.js +318 -0
  92. package/src/desk/ui/views-topics.js +87 -0
  93. package/src/desk/verbs.ts +361 -0
  94. package/src/doctor.ts +212 -0
  95. package/src/drain.ts +14 -0
  96. package/src/engage/index.ts +217 -0
  97. package/src/generate/index.ts +110 -0
  98. package/src/generate/script.ts +152 -0
  99. package/src/generate/title.ts +78 -0
  100. package/src/help.ts +233 -0
  101. package/src/home.ts +45 -0
  102. package/src/llm/client.ts +177 -0
  103. package/src/log.ts +7 -0
  104. package/src/oauth/tokens.ts +189 -0
  105. package/src/oauth/vault.ts +72 -0
  106. package/src/pipeline/review.ts +642 -0
  107. package/src/pipeline/run.ts +443 -0
  108. package/src/pipeline/series-guard.ts +26 -0
  109. package/src/pipeline/source-fetch.ts +69 -0
  110. package/src/pipeline/stages.ts +728 -0
  111. package/src/pipeline/topics-source.ts +90 -0
  112. package/src/product/commands.ts +296 -0
  113. package/src/product/config-file.ts +38 -0
  114. package/src/product/engine-choice.ts +89 -0
  115. package/src/product/engines.ts +103 -0
  116. package/src/product/insights.ts +50 -0
  117. package/src/product/keys.ts +67 -0
  118. package/src/product/paths.ts +18 -0
  119. package/src/product/probes.ts +88 -0
  120. package/src/product/push-flow.ts +90 -0
  121. package/src/product/render-video.ts +21 -0
  122. package/src/product/short.ts +62 -0
  123. package/src/product/update.ts +32 -0
  124. package/src/project/canonical.ts +14 -0
  125. package/src/project/commands.ts +177 -0
  126. package/src/project/dashboard-status.ts +28 -0
  127. package/src/project/discover.ts +19 -0
  128. package/src/project/index-file.ts +73 -0
  129. package/src/project/marker.ts +87 -0
  130. package/src/project/migrate.ts +201 -0
  131. package/src/project/names.ts +27 -0
  132. package/src/project/notice.ts +16 -0
  133. package/src/project/open.ts +88 -0
  134. package/src/project/scaffold.ts +112 -0
  135. package/src/project/templates.ts +42 -0
  136. package/src/project/videos.ts +64 -0
  137. package/src/publish/facebook.ts +91 -0
  138. package/src/publish/index.ts +12 -0
  139. package/src/publish/instagram.ts +97 -0
  140. package/src/publish/rate.ts +62 -0
  141. package/src/publish/session.ts +242 -0
  142. package/src/publish/tiktok.ts +202 -0
  143. package/src/publish/youtube.ts +177 -0
  144. package/src/queue/desk-ops.ts +1170 -0
  145. package/src/queue/seal.ts +3 -0
  146. package/src/queue/store.ts +1006 -0
  147. package/src/remotion/AiLabel.tsx +26 -0
  148. package/src/remotion/Root.tsx +73 -0
  149. package/src/remotion/defaults.ts +26 -0
  150. package/src/remotion/films/claude/ClaudeFilm.tsx +1014 -0
  151. package/src/remotion/films/engine/EngineMark.tsx +17 -0
  152. package/src/remotion/films/rea/ReaShort.tsx +552 -0
  153. package/src/remotion/films/rea/drawings.tsx +907 -0
  154. package/src/remotion/films/rea/timing.ts +144 -0
  155. package/src/remotion/index.ts +4 -0
  156. package/src/remotion/templates/EditorialSplit.tsx +39 -0
  157. package/src/remotion/templates/KineticType.tsx +39 -0
  158. package/src/remotion/templates/SignalBoard.tsx +50 -0
  159. package/src/remotion/timing.ts +22 -0
  160. package/src/render/chrome.ts +78 -0
  161. package/src/render/engine-mark.ts +29 -0
  162. package/src/render/framey-template.ts +130 -0
  163. package/src/render/html-engine.ts +149 -0
  164. package/src/render/node-crypto-stub.ts +11 -0
  165. package/src/render/probe.ts +29 -0
  166. package/src/render/props.ts +17 -0
  167. package/src/render/vertical-short.ts +35 -0
  168. package/src/render/webpack.ts +33 -0
  169. package/src/render/worker.ts +65 -0
  170. package/src/scene/assets/fonts/TitanOne-OFL.txt +94 -0
  171. package/src/scene/assets/fonts/titan-one.woff2 +0 -0
  172. package/src/scene/assets/gsap/LICENSE.txt +8 -0
  173. package/src/scene/assets/gsap/gsap.min.js +11 -0
  174. package/src/scene/audio.ts +54 -0
  175. package/src/scene/blocks/LICENSE +190 -0
  176. package/src/scene/blocks/NOTICE +5 -0
  177. package/src/scene/blocks/bar-chart-race/bar-chart-race.html +585 -0
  178. package/src/scene/blocks/beat-freeze-cut/beat-freeze-cut.html +874 -0
  179. package/src/scene/blocks/camcorder-hud/camcorder-hud.html +164 -0
  180. package/src/scene/blocks/camera-dolly-zoom/camera-dolly-zoom.html +355 -0
  181. package/src/scene/blocks/code-diff/code-diff.html +817 -0
  182. package/src/scene/blocks/code-snippet-apple-terminal-pro/code-snippet-apple-terminal-pro.html +248 -0
  183. package/src/scene/blocks/code-typing/code-typing.html +764 -0
  184. package/src/scene/blocks/data-chart/data-chart.html +452 -0
  185. package/src/scene/blocks/flowchart-vertical/flowchart-vertical.html +454 -0
  186. package/src/scene/blocks/hw-scribble-transition/hw-scribble-transition.html +153 -0
  187. package/src/scene/blocks/index.json +824 -0
  188. package/src/scene/blocks/lt-accent-underline/lt-accent-underline.html +107 -0
  189. package/src/scene/blocks/lt-bold-block/lt-bold-block.html +109 -0
  190. package/src/scene/blocks/lt-clean-bar/lt-clean-bar.html +112 -0
  191. package/src/scene/blocks/lt-dark-card/lt-dark-card.html +111 -0
  192. package/src/scene/blocks/lt-kicker-name/lt-kicker-name.html +114 -0
  193. package/src/scene/blocks/lt-mask-reveal/lt-mask-reveal.html +120 -0
  194. package/src/scene/blocks/lt-neon-border/lt-neon-border.html +391 -0
  195. package/src/scene/blocks/lt-stack-bars/lt-stack-bars.html +109 -0
  196. package/src/scene/blocks/macos-notification/macos-notification.html +194 -0
  197. package/src/scene/blocks/mk-background/mk-background.html +236 -0
  198. package/src/scene/blocks/mk-callout-highlight/mk-callout-highlight.html +183 -0
  199. package/src/scene/blocks/mk-clone-wall-transition/mk-clone-wall-transition.html +226 -0
  200. package/src/scene/blocks/mk-line-graph/mk-line-graph.html +293 -0
  201. package/src/scene/blocks/mk-progress-stat/mk-progress-stat.html +186 -0
  202. package/src/scene/blocks/mk-specs-list/mk-specs-list.html +223 -0
  203. package/src/scene/blocks/news-ticker/news-ticker.html +409 -0
  204. package/src/scene/blocks/organic-light-leak-overlay/organic-light-leak-overlay.html +126 -0
  205. package/src/scene/blocks/oscilloscope-trace/oscilloscope-trace.html +519 -0
  206. package/src/scene/blocks/snow/snow.html +205 -0
  207. package/src/scene/blocks/split-flap-board/split-flap-board.html +347 -0
  208. package/src/scene/blocks/spotify-card/spotify-card.html +294 -0
  209. package/src/scene/blocks/starfield/starfield.html +188 -0
  210. package/src/scene/blocks/thread-message-stack/thread-message-stack.html +239 -0
  211. package/src/scene/blocks/week-in-merges/week-in-merges.html +470 -0
  212. package/src/scene/blocks/x-post/x-post.html +437 -0
  213. package/src/scene/blocks/yt-comment-card/yt-comment-card.html +319 -0
  214. package/src/scene/blocks/yt-lcd-background/yt-lcd-background.html +307 -0
  215. package/src/scene/blocks/yt-prism-title/yt-prism-title.html +205 -0
  216. package/src/scene/blocks.ts +229 -0
  217. package/src/scene/command.ts +272 -0
  218. package/src/scene/figure.ts +181 -0
  219. package/src/scene/glyphs.ts +107 -0
  220. package/src/scene/init.ts +86 -0
  221. package/src/scene/inspect/css-tree.d.ts +6 -0
  222. package/src/scene/inspect/page-scripts.ts +272 -0
  223. package/src/scene/inspect/report.ts +405 -0
  224. package/src/scene/inspect/run.ts +200 -0
  225. package/src/scene/inspect/source.ts +236 -0
  226. package/src/scene/label.ts +131 -0
  227. package/src/scene/net-guard.ts +74 -0
  228. package/src/scene/render.ts +292 -0
  229. package/src/scene/runtime/browser.ts +199 -0
  230. package/src/scene/runtime/core.ts +181 -0
  231. package/src/scene/runtime/react.tsx +115 -0
  232. package/src/scene/runtime/transitions.ts +133 -0
  233. package/src/scene/sanitize.ts +181 -0
  234. package/src/scene/scene.ts +152 -0
  235. package/src/scene/studio-command.ts +48 -0
  236. package/src/scene/studio-skin.ts +59 -0
  237. package/src/scene/studio.ts +337 -0
  238. package/src/scene/supply.ts +111 -0
  239. package/src/scene/timing.ts +288 -0
  240. package/src/scene/transitions/LICENSE +190 -0
  241. package/src/scene/transitions/NOTICE +5 -0
  242. package/src/scene/transitions/SOURCE.json +24 -0
  243. package/src/scene/transitions/transitions.global.js +38 -0
  244. package/src/scene/transitions.ts +26 -0
  245. package/src/service/all-projects.ts +153 -0
  246. package/src/service/commands.ts +256 -0
  247. package/src/service/due.ts +82 -0
  248. package/src/service/lock.ts +101 -0
  249. package/src/service/log-file.ts +56 -0
  250. package/src/service/state.ts +41 -0
  251. package/src/service/units.ts +90 -0
  252. package/src/service/worker.ts +51 -0
  253. package/src/skill-agents.ts +74 -0
  254. package/src/skill-install.ts +334 -0
  255. package/src/sync-write.ts +21 -0
  256. package/src/tick-report.ts +205 -0
  257. package/src/tts.ts +124 -0
  258. package/vendor/@vfrey/contracts/dist/account.d.ts +97 -0
  259. package/vendor/@vfrey/contracts/dist/account.js +27 -0
  260. package/vendor/@vfrey/contracts/dist/checks.d.ts +8 -0
  261. package/vendor/@vfrey/contracts/dist/checks.js +1 -0
  262. package/vendor/@vfrey/contracts/dist/credentials/crypto.d.ts +4 -0
  263. package/vendor/@vfrey/contracts/dist/credentials/crypto.js +38 -0
  264. package/vendor/@vfrey/contracts/dist/domain/advice-persona.d.ts +10 -0
  265. package/vendor/@vfrey/contracts/dist/domain/advice-persona.js +24 -0
  266. package/vendor/@vfrey/contracts/dist/domain/backoff.d.ts +13 -0
  267. package/vendor/@vfrey/contracts/dist/domain/backoff.js +27 -0
  268. package/vendor/@vfrey/contracts/dist/domain/cadence.d.ts +29 -0
  269. package/vendor/@vfrey/contracts/dist/domain/cadence.js +95 -0
  270. package/vendor/@vfrey/contracts/dist/domain/creators.d.ts +146 -0
  271. package/vendor/@vfrey/contracts/dist/domain/creators.js +2 -0
  272. package/vendor/@vfrey/contracts/dist/domain/disclosure.d.ts +127 -0
  273. package/vendor/@vfrey/contracts/dist/domain/disclosure.js +250 -0
  274. package/vendor/@vfrey/contracts/dist/domain/errors.d.ts +34 -0
  275. package/vendor/@vfrey/contracts/dist/domain/errors.js +68 -0
  276. package/vendor/@vfrey/contracts/dist/domain/redact.d.ts +1 -0
  277. package/vendor/@vfrey/contracts/dist/domain/redact.js +21 -0
  278. package/vendor/@vfrey/contracts/dist/domain/revenue.d.ts +13 -0
  279. package/vendor/@vfrey/contracts/dist/domain/revenue.js +16 -0
  280. package/vendor/@vfrey/contracts/dist/domain/safety.d.ts +20 -0
  281. package/vendor/@vfrey/contracts/dist/domain/safety.js +61 -0
  282. package/vendor/@vfrey/contracts/dist/domain/similarity.d.ts +13 -0
  283. package/vendor/@vfrey/contracts/dist/domain/similarity.js +100 -0
  284. package/vendor/@vfrey/contracts/dist/domain/templates.d.ts +18 -0
  285. package/vendor/@vfrey/contracts/dist/domain/templates.js +67 -0
  286. package/vendor/@vfrey/contracts/dist/domain/tiktok-chunks.d.ts +19 -0
  287. package/vendor/@vfrey/contracts/dist/domain/tiktok-chunks.js +52 -0
  288. package/vendor/@vfrey/contracts/dist/domain/topics.d.ts +78 -0
  289. package/vendor/@vfrey/contracts/dist/domain/topics.js +4 -0
  290. package/vendor/@vfrey/contracts/dist/domain/types.d.ts +216 -0
  291. package/vendor/@vfrey/contracts/dist/domain/types.js +1 -0
  292. package/vendor/@vfrey/contracts/dist/domain/variation.d.ts +57 -0
  293. package/vendor/@vfrey/contracts/dist/domain/variation.js +278 -0
  294. package/vendor/@vfrey/contracts/dist/events.d.ts +20 -0
  295. package/vendor/@vfrey/contracts/dist/events.js +1 -0
  296. package/vendor/@vfrey/contracts/dist/http.d.ts +11 -0
  297. package/vendor/@vfrey/contracts/dist/http.js +37 -0
  298. package/vendor/@vfrey/contracts/dist/index.d.ts +22 -0
  299. package/vendor/@vfrey/contracts/dist/index.js +22 -0
  300. package/vendor/@vfrey/contracts/dist/log.d.ts +2 -0
  301. package/vendor/@vfrey/contracts/dist/log.js +10 -0
  302. package/vendor/@vfrey/contracts/dist/mail.d.ts +55 -0
  303. package/vendor/@vfrey/contracts/dist/mail.js +1 -0
  304. package/vendor/@vfrey/contracts/package.json +18 -0
  305. package/vendor/@vfrey/ingest/dist/index.d.ts +41 -0
  306. package/vendor/@vfrey/ingest/dist/index.js +221 -0
  307. package/vendor/@vfrey/ingest/dist/parse.d.ts +5 -0
  308. package/vendor/@vfrey/ingest/dist/parse.js +165 -0
  309. package/vendor/@vfrey/ingest/package.json +21 -0
  310. package/vendor/framey/LICENSE +190 -0
  311. package/vendor/framey/NOTICE +15 -0
  312. package/vendor/framey/SOURCE.json +24 -0
  313. package/vendor/framey/STUDIO-SOURCE.json +9 -0
  314. package/vendor/framey/bin/framey-localize-fonts.mjs +12 -0
  315. package/vendor/framey/bin/framey.mjs +16 -0
  316. package/vendor/framey/dist/add-VMJD5KBS.js +75 -0
  317. package/vendor/framey/dist/animatedGifPrep-QPKGJ6PM.js +43 -0
  318. package/vendor/framey/dist/api.d.ts +211 -0
  319. package/vendor/framey/dist/api.js +76 -0
  320. package/vendor/framey/dist/appHistory-WW56FZTT.js +31 -0
  321. package/vendor/framey/dist/asset-WQKGOELE.js +26 -0
  322. package/vendor/framey/dist/audio-RSJWVWRA.js +1936 -0
  323. package/vendor/framey/dist/batchRender-3HPICDCT.js +366 -0
  324. package/vendor/framey/dist/beats-HL2BDUZI.js +273 -0
  325. package/vendor/framey/dist/benchmark-RWCWHI5Z.js +230 -0
  326. package/vendor/framey/dist/browser-ECYET3Q2.js +206 -0
  327. package/vendor/framey/dist/bundleWithLocalizedFonts-ALYBQEQT.js +52 -0
  328. package/vendor/framey/dist/captureCompositionFrame-4DA6SEH2.js +94 -0
  329. package/vendor/framey/dist/catalog-5JVDEUWK.js +979 -0
  330. package/vendor/framey/dist/catch-up-NEBCL5NO.js +106 -0
  331. package/vendor/framey/dist/check-F5N544ML.js +111 -0
  332. package/vendor/framey/dist/checkBrowser-LZ66CMJG.js +110 -0
  333. package/vendor/framey/dist/chunk-2K7Z2HVP.js +372 -0
  334. package/vendor/framey/dist/chunk-2UZQHDM7.js +323 -0
  335. package/vendor/framey/dist/chunk-2X4PQEYM.js +34 -0
  336. package/vendor/framey/dist/chunk-3422KMTD.js +168 -0
  337. package/vendor/framey/dist/chunk-3FYD4YEK.js +72 -0
  338. package/vendor/framey/dist/chunk-3GXQPCJC.js +682 -0
  339. package/vendor/framey/dist/chunk-3LM6YPBR.js +179 -0
  340. package/vendor/framey/dist/chunk-442JNXRM.js +20 -0
  341. package/vendor/framey/dist/chunk-4BNN5FGX.js +182 -0
  342. package/vendor/framey/dist/chunk-4P7NX5BM.js +11532 -0
  343. package/vendor/framey/dist/chunk-4UMPIPCQ.js +88 -0
  344. package/vendor/framey/dist/chunk-4YYJOFKS.js +28 -0
  345. package/vendor/framey/dist/chunk-54HJ63Q2.js +29 -0
  346. package/vendor/framey/dist/chunk-5ETJX6WM.js +89 -0
  347. package/vendor/framey/dist/chunk-5SG54JRS.js +68 -0
  348. package/vendor/framey/dist/chunk-634HSJ3J.js +58 -0
  349. package/vendor/framey/dist/chunk-66LREXGS.js +48 -0
  350. package/vendor/framey/dist/chunk-6BEFEWFB.js +25 -0
  351. package/vendor/framey/dist/chunk-6BNTGNGD.js +286 -0
  352. package/vendor/framey/dist/chunk-6DDPOHMK.js +140 -0
  353. package/vendor/framey/dist/chunk-6GV5XSOR.js +214 -0
  354. package/vendor/framey/dist/chunk-6JR2XUEE.js +127 -0
  355. package/vendor/framey/dist/chunk-73QVATIM.js +362 -0
  356. package/vendor/framey/dist/chunk-7FMUTGOH.js +279 -0
  357. package/vendor/framey/dist/chunk-7JQFJ6JJ.js +291 -0
  358. package/vendor/framey/dist/chunk-AHPGAESX.js +113 -0
  359. package/vendor/framey/dist/chunk-AHX34EFP.js +15 -0
  360. package/vendor/framey/dist/chunk-AJ5CSAEZ.js +487 -0
  361. package/vendor/framey/dist/chunk-B7RJV74O.js +5047 -0
  362. package/vendor/framey/dist/chunk-BL4U6U52.js +254 -0
  363. package/vendor/framey/dist/chunk-BSQ7XANM.js +210 -0
  364. package/vendor/framey/dist/chunk-BZ56MTDX.js +6 -0
  365. package/vendor/framey/dist/chunk-C5BO7PMT.js +282 -0
  366. package/vendor/framey/dist/chunk-CFUCHO4T.js +358 -0
  367. package/vendor/framey/dist/chunk-CZGHFATT.js +31 -0
  368. package/vendor/framey/dist/chunk-DLA44CMS.js +5649 -0
  369. package/vendor/framey/dist/chunk-DPVXBVLL.js +31292 -0
  370. package/vendor/framey/dist/chunk-DQBY7FRR.js +397 -0
  371. package/vendor/framey/dist/chunk-EAMLBAHA.js +154 -0
  372. package/vendor/framey/dist/chunk-EOVYQ3IG.js +143 -0
  373. package/vendor/framey/dist/chunk-EVMY7IPL.js +612 -0
  374. package/vendor/framey/dist/chunk-FG4BBFZI.js +122 -0
  375. package/vendor/framey/dist/chunk-FI4I7CME.js +56 -0
  376. package/vendor/framey/dist/chunk-FLREUEHW.js +2081 -0
  377. package/vendor/framey/dist/chunk-FUFP7A7S.js +1126 -0
  378. package/vendor/framey/dist/chunk-FV3PIKGH.js +56 -0
  379. package/vendor/framey/dist/chunk-FXMKHHPO.js +123 -0
  380. package/vendor/framey/dist/chunk-GGZAM5VH.js +1187 -0
  381. package/vendor/framey/dist/chunk-GKZEVJIB.js +39 -0
  382. package/vendor/framey/dist/chunk-GMECXFAN.js +57 -0
  383. package/vendor/framey/dist/chunk-GNEFDLFB.js +621 -0
  384. package/vendor/framey/dist/chunk-GPMLSOEG.js +19274 -0
  385. package/vendor/framey/dist/chunk-GPYVT5EE.js +59 -0
  386. package/vendor/framey/dist/chunk-H6IEMZEV.js +40 -0
  387. package/vendor/framey/dist/chunk-HEFQCIXR.js +170 -0
  388. package/vendor/framey/dist/chunk-HFQ4CWHA.js +118 -0
  389. package/vendor/framey/dist/chunk-HPDTCOKE.js +304 -0
  390. package/vendor/framey/dist/chunk-HTUHQKDB.js +548 -0
  391. package/vendor/framey/dist/chunk-HU2SPFNG.js +103 -0
  392. package/vendor/framey/dist/chunk-HVW7ABXD.js +19 -0
  393. package/vendor/framey/dist/chunk-IG7NDKXO.js +26 -0
  394. package/vendor/framey/dist/chunk-II3J3WXK.js +246 -0
  395. package/vendor/framey/dist/chunk-IR35BCLK.js +13 -0
  396. package/vendor/framey/dist/chunk-ISN5GRYI.js +20 -0
  397. package/vendor/framey/dist/chunk-IUONB55J.js +669 -0
  398. package/vendor/framey/dist/chunk-IVSUQR2B.js +161 -0
  399. package/vendor/framey/dist/chunk-IXU6PQSW.js +259 -0
  400. package/vendor/framey/dist/chunk-IZCW2NKT.js +29 -0
  401. package/vendor/framey/dist/chunk-JGXJU5PF.js +68 -0
  402. package/vendor/framey/dist/chunk-JHOCK3DG.js +27 -0
  403. package/vendor/framey/dist/chunk-JVBRJMOP.js +121 -0
  404. package/vendor/framey/dist/chunk-K4MJX7SR.js +17 -0
  405. package/vendor/framey/dist/chunk-K4WKGXRC.js +18 -0
  406. package/vendor/framey/dist/chunk-KGPLIH7B.js +127 -0
  407. package/vendor/framey/dist/chunk-KLIKCX6Q.js +63 -0
  408. package/vendor/framey/dist/chunk-KXTKKBOC.js +61 -0
  409. package/vendor/framey/dist/chunk-KZI44OPA.js +185 -0
  410. package/vendor/framey/dist/chunk-LEKZNRKI.js +45 -0
  411. package/vendor/framey/dist/chunk-LFGJWOVA.js +61 -0
  412. package/vendor/framey/dist/chunk-LLMSX6V6.js +17 -0
  413. package/vendor/framey/dist/chunk-LTGTN2TH.js +195 -0
  414. package/vendor/framey/dist/chunk-M2WBOQ2Q.js +54 -0
  415. package/vendor/framey/dist/chunk-MI5FTLYK.js +399 -0
  416. package/vendor/framey/dist/chunk-MLQP2QUF.js +1809 -0
  417. package/vendor/framey/dist/chunk-MMQ52NIZ.js +956 -0
  418. package/vendor/framey/dist/chunk-ND46XKK3.js +742 -0
  419. package/vendor/framey/dist/chunk-NYEXNSHM.js +504 -0
  420. package/vendor/framey/dist/chunk-O4YRB27L.js +57 -0
  421. package/vendor/framey/dist/chunk-O7BGSQ5F.js +92 -0
  422. package/vendor/framey/dist/chunk-OFQWTKPW.js +117 -0
  423. package/vendor/framey/dist/chunk-P5ZBLXJ6.js +91 -0
  424. package/vendor/framey/dist/chunk-P6LJ4Y32.js +4662 -0
  425. package/vendor/framey/dist/chunk-PKZ7RK5N.js +281 -0
  426. package/vendor/framey/dist/chunk-PURHAXFL.js +15 -0
  427. package/vendor/framey/dist/chunk-Q5X2B5WT.js +29 -0
  428. package/vendor/framey/dist/chunk-QAMKOG67.js +248 -0
  429. package/vendor/framey/dist/chunk-R6YBK4XX.js +514 -0
  430. package/vendor/framey/dist/chunk-RGLQURIX.js +2997 -0
  431. package/vendor/framey/dist/chunk-RNV3DM4S.js +3573 -0
  432. package/vendor/framey/dist/chunk-ROEW726S.js +4638 -0
  433. package/vendor/framey/dist/chunk-RQVDTPGD.js +6 -0
  434. package/vendor/framey/dist/chunk-RVZHGOGR.js +26 -0
  435. package/vendor/framey/dist/chunk-RXATE6FZ.js +385 -0
  436. package/vendor/framey/dist/chunk-S3S4TGEH.js +424 -0
  437. package/vendor/framey/dist/chunk-SDYDNHEE.js +11202 -0
  438. package/vendor/framey/dist/chunk-SSWBU67I.js +173 -0
  439. package/vendor/framey/dist/chunk-ST35C4K6.js +28 -0
  440. package/vendor/framey/dist/chunk-SZNTYTIV.js +990 -0
  441. package/vendor/framey/dist/chunk-T2EUWCJE.js +29 -0
  442. package/vendor/framey/dist/chunk-T6AGUTZJ.js +444 -0
  443. package/vendor/framey/dist/chunk-THJALHFJ.js +11131 -0
  444. package/vendor/framey/dist/chunk-TIQB63MX.js +18128 -0
  445. package/vendor/framey/dist/chunk-U242RTCT.js +134 -0
  446. package/vendor/framey/dist/chunk-UJZREAV6.js +3901 -0
  447. package/vendor/framey/dist/chunk-UMD3V7CU.js +264 -0
  448. package/vendor/framey/dist/chunk-UOFAE5RF.js +42 -0
  449. package/vendor/framey/dist/chunk-UTEIUGAZ.js +29 -0
  450. package/vendor/framey/dist/chunk-VAS6HQX3.js +138 -0
  451. package/vendor/framey/dist/chunk-VC76R6W2.js +27 -0
  452. package/vendor/framey/dist/chunk-VFZ7W5W7.js +226 -0
  453. package/vendor/framey/dist/chunk-VHNLZAE2.js +348 -0
  454. package/vendor/framey/dist/chunk-VMC4WSH5.js +278 -0
  455. package/vendor/framey/dist/chunk-VORQIH64.js +108 -0
  456. package/vendor/framey/dist/chunk-VTXFRIHO.js +186 -0
  457. package/vendor/framey/dist/chunk-W2LGJSEN.js +182 -0
  458. package/vendor/framey/dist/chunk-WKBM7NDG.js +32 -0
  459. package/vendor/framey/dist/chunk-WMQNIQDJ.js +2057 -0
  460. package/vendor/framey/dist/chunk-WN4XZC5F.js +504 -0
  461. package/vendor/framey/dist/chunk-WQ6ZXHFQ.js +133 -0
  462. package/vendor/framey/dist/chunk-X7HBSTCZ.js +53 -0
  463. package/vendor/framey/dist/chunk-X7MTZ4T2.js +6 -0
  464. package/vendor/framey/dist/chunk-XPTOJZJF.js +308 -0
  465. package/vendor/framey/dist/chunk-XT6MXC7A.js +6 -0
  466. package/vendor/framey/dist/chunk-XT7X6QCP.js +6 -0
  467. package/vendor/framey/dist/chunk-XTMDWNEC.js +2820 -0
  468. package/vendor/framey/dist/chunk-XUHOIDKG.js +6 -0
  469. package/vendor/framey/dist/chunk-XX7LTW5Y.js +138 -0
  470. package/vendor/framey/dist/chunk-Y3YGTZEG.js +382 -0
  471. package/vendor/framey/dist/chunk-Y5SBSGN7.js +346 -0
  472. package/vendor/framey/dist/chunk-YCMVI4MZ.js +625 -0
  473. package/vendor/framey/dist/chunk-YOR4CTCE.js +261 -0
  474. package/vendor/framey/dist/chunk-YPRBGITP.js +2748 -0
  475. package/vendor/framey/dist/chunk-ZKDMAOFU.js +32 -0
  476. package/vendor/framey/dist/chunk-ZW6DURPF.js +1318 -0
  477. package/vendor/framey/dist/clean-ZJOGDKDM.js +336 -0
  478. package/vendor/framey/dist/cli.js +439 -0
  479. package/vendor/framey/dist/cloudrun-HGJ3B6ZV.js +767 -0
  480. package/vendor/framey/dist/commands/contrast-audit.browser.js +643 -0
  481. package/vendor/framey/dist/commands/layout-audit.browser.js +2914 -0
  482. package/vendor/framey/dist/commands/motion-sample.browser.js +74 -0
  483. package/vendor/framey/dist/commands/motion-signature.browser.js +475 -0
  484. package/vendor/framey/dist/compare-W7UY3BAZ.js +463 -0
  485. package/vendor/framey/dist/compiler-TM3W6GYF.js +136 -0
  486. package/vendor/framey/dist/component-QF5VGYMU.js +176 -0
  487. package/vendor/framey/dist/compositions-XT3PMNDF.js +238 -0
  488. package/vendor/framey/dist/contactSheet-7W6GYHBQ.js +24 -0
  489. package/vendor/framey/dist/deploy-6FJPWKF2.js +299 -0
  490. package/vendor/framey/dist/destroy-HE2RIPKZ.js +57 -0
  491. package/vendor/framey/dist/deterministicFonts-RADD3BSX.js +50 -0
  492. package/vendor/framey/dist/dist-4S2FGGVY.js +422 -0
  493. package/vendor/framey/dist/dist-BE4B2EZE.js +32 -0
  494. package/vendor/framey/dist/dist-EWXJGN63.js +129 -0
  495. package/vendor/framey/dist/docs-VKIRFEEX.js +131 -0
  496. package/vendor/framey/dist/doctor-2UNJ2G7U.js +74 -0
  497. package/vendor/framey/dist/dom-37K6YOH4.js +14 -0
  498. package/vendor/framey/dist/dotEnv-7PZQTVIM.js +54 -0
  499. package/vendor/framey/dist/events-ACY3P2PA.js +76 -0
  500. package/vendor/framey/dist/events-IHB3B2MK.js +69 -0
  501. package/vendor/framey/dist/ffmpeg-DR5LGGSK.js +63 -0
  502. package/vendor/framey/dist/figma-BODVUPHB.js +63 -0
  503. package/vendor/framey/dist/fontData.generated-NXAOI4GH.js +13 -0
  504. package/vendor/framey/dist/fontLocalizeCli.js +142 -0
  505. package/vendor/framey/dist/gpuPolicy-XLEXORZY.js +49 -0
  506. package/vendor/framey/dist/grade-compare-GAXFQ74C.js +661 -0
  507. package/vendor/framey/dist/gsapParser-IEUSLYDJ.js +2885 -0
  508. package/vendor/framey/dist/gsapParserAcorn-LZJKCFQI.js +30 -0
  509. package/vendor/framey/dist/help-VCB5X2HS.js +184 -0
  510. package/vendor/framey/dist/history-ENGZEVFT.js +471 -0
  511. package/vendor/framey/dist/hyperframe.manifest.json +22 -0
  512. package/vendor/framey/dist/hyperframe.runtime.iife.js +1132 -0
  513. package/vendor/framey/dist/hyperframes-player.global.js +478 -0
  514. package/vendor/framey/dist/hyperframes-slideshow.global.js +148 -0
  515. package/vendor/framey/dist/info-WPCJHBMU.js +182 -0
  516. package/vendor/framey/dist/init-G4WGLYGD.js +1176 -0
  517. package/vendor/framey/dist/inspect-5IQ6CNEQ.js +106 -0
  518. package/vendor/framey/dist/installer-ML4HWUV7.js +40 -0
  519. package/vendor/framey/dist/keyframes-Q6XJO7VW.js +2755 -0
  520. package/vendor/framey/dist/lambda-A7JC74JF.js +468 -0
  521. package/vendor/framey/dist/layout-YET6XNXA.js +95 -0
  522. package/vendor/framey/dist/lint-I7FZN2VJ.js +162 -0
  523. package/vendor/framey/dist/lintProject-PDB3UN72.js +30 -0
  524. package/vendor/framey/dist/manager-CD6LJ7ZN.js +45 -0
  525. package/vendor/framey/dist/manager-WA4F2GST.js +67 -0
  526. package/vendor/framey/dist/media-treatment-BXYS4WVA.js +1030 -0
  527. package/vendor/framey/dist/media-use-LWH3MANK.js +113 -0
  528. package/vendor/framey/dist/models-K363FYM4.js +195 -0
  529. package/vendor/framey/dist/motionShot-GPAVWXLH.js +640 -0
  530. package/vendor/framey/dist/normalize-FASIPBUM.js +24 -0
  531. package/vendor/framey/dist/normalize-audio-VDWYRHN6.js +268 -0
  532. package/vendor/framey/dist/open-E3TB6P6J.js +128 -0
  533. package/vendor/framey/dist/parakeetRunner-UP34UOI2.js +58 -0
  534. package/vendor/framey/dist/pipeline-VXIUYEBU.js +64 -0
  535. package/vendor/framey/dist/play-BUTDQ4DV.js +353 -0
  536. package/vendor/framey/dist/policies-OLDYGFK5.js +309 -0
  537. package/vendor/framey/dist/preflight-2KZ2GWAZ.js +55 -0
  538. package/vendor/framey/dist/present-GXYSM7NX.js +353 -0
  539. package/vendor/framey/dist/preview-EKZ33JOJ.js +1910 -0
  540. package/vendor/framey/dist/producer-SKU5EV3J.js +13 -0
  541. package/vendor/framey/dist/progress-ZWB4Z4ET.js +76 -0
  542. package/vendor/framey/dist/projectConfig-3MZAYVTS.js +60 -0
  543. package/vendor/framey/dist/publication-DTKWNF74.js +33 -0
  544. package/vendor/framey/dist/remove-background-OY5L7XN2.js +265 -0
  545. package/vendor/framey/dist/render-CDV4GDFX.js +187 -0
  546. package/vendor/framey/dist/render-YE5YAMOD.js +2620 -0
  547. package/vendor/framey/dist/render-batch-ZAMFPCLL.js +274 -0
  548. package/vendor/framey/dist/renderSetupWorker.js +120 -0
  549. package/vendor/framey/dist/resolver-D5BIPSEW.js +42 -0
  550. package/vendor/framey/dist/runtimeVersion.js +18 -0
  551. package/vendor/framey/dist/sam-WFZXI4F7.js +23 -0
  552. package/vendor/framey/dist/shaderTransitionWorker.js +44 -0
  553. package/vendor/framey/dist/sherpa-RQWLV7I3.js +79 -0
  554. package/vendor/framey/dist/sherpaWorker.js +84 -0
  555. package/vendor/framey/dist/sites-AMOVABTK.js +54 -0
  556. package/vendor/framey/dist/skill-ZHVLH7KX.js +15 -0
  557. package/vendor/framey/dist/slideshow-SJGK4RQS.js +24 -0
  558. package/vendor/framey/dist/snapshot-TUXL6LBQ.js +1515 -0
  559. package/vendor/framey/dist/src-JHQGB2S6.js +215 -0
  560. package/vendor/framey/dist/src-Z5PGEMXB.js +532 -0
  561. package/vendor/framey/dist/state-B6H3WHCF.js +28 -0
  562. package/vendor/framey/dist/staticProjectServer-DFVZOUGI.js +63 -0
  563. package/vendor/framey/dist/studio/assets/hyperframes-player-DLaKjw0L.js +478 -0
  564. package/vendor/framey/dist/studio/assets/index-BX3KHhGX.js +71 -0
  565. package/vendor/framey/dist/studio/assets/index-CYbvOVp-.css +1 -0
  566. package/vendor/framey/dist/studio/assets/index-Dp3QEUGL.js +402 -0
  567. package/vendor/framey/dist/studio/assets/index-qrTAXbqc.js +531 -0
  568. package/vendor/framey/dist/studio/favicon.svg +14 -0
  569. package/vendor/framey/dist/studio/icons/timeline/audio.svg +7 -0
  570. package/vendor/framey/dist/studio/icons/timeline/captions.svg +5 -0
  571. package/vendor/framey/dist/studio/icons/timeline/composition.svg +12 -0
  572. package/vendor/framey/dist/studio/icons/timeline/image.svg +18 -0
  573. package/vendor/framey/dist/studio/icons/timeline/music.svg +10 -0
  574. package/vendor/framey/dist/studio/icons/timeline/text.svg +3 -0
  575. package/vendor/framey/dist/studio/index.html +23 -0
  576. package/vendor/framey/dist/studio-api-2NECGRMB.js +179 -0
  577. package/vendor/framey/dist/studioSelectionClient-IUUPKUHZ.js +25 -0
  578. package/vendor/framey/dist/studioServer-N2OPUMOQ.js +1569 -0
  579. package/vendor/framey/dist/synthesize-PKTB5ATG.js +183 -0
  580. package/vendor/framey/dist/system-7F3UEHQT.js +27 -0
  581. package/vendor/framey/dist/telemetry-DQGPEKM6.js +145 -0
  582. package/vendor/framey/dist/telemetry-UN55N6U6.js +77 -0
  583. package/vendor/framey/dist/timeline-LHUUMK63.js +1295 -0
  584. package/vendor/framey/dist/tokens-OLECWDFK.js +92 -0
  585. package/vendor/framey/dist/transcribe-O7HQKMIV.js +331 -0
  586. package/vendor/framey/dist/transcribe-UJESPBT5.js +76 -0
  587. package/vendor/framey/dist/tts-YCCQHZD4.js +234 -0
  588. package/vendor/framey/dist/urlDownloader-H2LXLG4U.js +48 -0
  589. package/vendor/framey/dist/usage-HG4WMM7A.js +2167 -0
  590. package/vendor/framey/dist/validate-F2XMN6EV.js +87 -0
  591. package/vendor/framey/dist/vendor/npm/gsap@3.15.0/GSAP-LICENSE.txt +8 -0
  592. package/vendor/framey/dist/vendor/npm/gsap@3.15.0/dist/CustomEase.min.js +11 -0
  593. package/vendor/framey/dist/vendor/npm/gsap@3.15.0/dist/MotionPathPlugin.min.js +11 -0
  594. package/vendor/framey/dist/vendor/npm/gsap@3.15.0/dist/gsap.min.js +11 -0
  595. package/vendor/framey/dist/warmCheck.js +220 -0
  596. package/vendor/framey/dist/warmCheckClient.js +139 -0
  597. package/vendor/framey/dist/workspaceBuildCheck-XYD2YTFW.js +133 -0
  598. package/vendor/framey-player/LICENSE +190 -0
  599. package/vendor/framey-player/NOTICE +16 -0
  600. package/vendor/framey-player/SOURCE.json +6 -0
  601. package/vendor/framey-player/hyperframes-player.global.js +478 -0
  602. package/vendor/framey.pin +1 -0
  603. package/bin/index.js +0 -3
@@ -0,0 +1,3573 @@
1
+ import { createRequire as __hf_createRequire } from "node:module";
2
+ import { fileURLToPath as __hf_fileURLToPath } from "node:url";
3
+ import { dirname as __hf_dirname } from "node:path";
4
+ var require = __hf_createRequire(import.meta.url);
5
+ var __filename = __hf_fileURLToPath(import.meta.url);
6
+ var __dirname = __hf_dirname(__filename);
7
+ import {
8
+ HF_AUDIO_FX_ATTR,
9
+ HF_COLOR_GRADING_ATTR,
10
+ INLINED_FILE_ATTR,
11
+ RUNTIME_BOOTSTRAP_ATTR,
12
+ UNCONDITIONAL_CSS_KEY,
13
+ assignMediaRenderIds,
14
+ clampDurations,
15
+ compileTimingAttrs,
16
+ compositionStyle,
17
+ countPageRoot,
18
+ cssStyleMergeKey,
19
+ deferScriptsUntilFonts,
20
+ enumerateNestedCompositionHosts,
21
+ escapeInlineScriptSource,
22
+ executableScripts,
23
+ extractResolvedMedia,
24
+ extractedCompositionAssets,
25
+ getHyperframeRuntimeScript,
26
+ hasSameLink,
27
+ headStyleRuns,
28
+ injectDurations,
29
+ injectTagsAtHeadStart,
30
+ inlineScriptRuns,
31
+ insertRuntimeTag,
32
+ isJavaScriptType,
33
+ isTemplateEntry,
34
+ parseHTMLContent,
35
+ parseHostVariableValues,
36
+ planCompositionAssembly,
37
+ readDeclaredDefaults,
38
+ shouldClampResolvedMediaDuration,
39
+ stripEmbeddedRuntimeScripts,
40
+ styleElementsFor,
41
+ warnUnknownEnumValues
42
+ } from "./chunk-UJZREAV6.js";
43
+ import {
44
+ cssVariableName
45
+ } from "./chunk-VC76R6W2.js";
46
+ import {
47
+ isSafePath,
48
+ resolveWithinProject
49
+ } from "./chunk-OFQWTKPW.js";
50
+ import {
51
+ lintHyperframeHtml
52
+ } from "./chunk-4P7NX5BM.js";
53
+ import {
54
+ checkSubCompositionUsability,
55
+ resolveSubCompositionContent
56
+ } from "./chunk-MMQ52NIZ.js";
57
+ import {
58
+ CSS_URL_RE,
59
+ decodeCssEscapes,
60
+ decodeWellFormedEscapes,
61
+ decodedUrlPath,
62
+ encodeUrlPath,
63
+ isNonRelativeUrl,
64
+ rewriteAssetPath,
65
+ rewriteAssetPaths,
66
+ rewriteCssAssetUrls,
67
+ rewriteInlineStyleAssetUrls,
68
+ splitUrlSuffix
69
+ } from "./chunk-BSQ7XANM.js";
70
+ import {
71
+ parseHTML
72
+ } from "./chunk-SDYDNHEE.js";
73
+
74
+ // ../core/dist/compiler/htmlCompiler.js
75
+ import { resolve } from "path";
76
+ function resolveMediaSrc(src, projectDir) {
77
+ return src.startsWith("http://") || src.startsWith("https://") ? src : resolve(projectDir, decodedUrlPath(src));
78
+ }
79
+ async function compileHtml(rawHtml, projectDir, probeMediaDuration) {
80
+ const { html: staticCompiled, unresolved } = compileTimingAttrs(rawHtml);
81
+ let html = staticCompiled;
82
+ if (!probeMediaDuration)
83
+ return html;
84
+ const mediaUnresolved = unresolved.filter((el) => el.tagName === "video" || el.tagName === "audio");
85
+ if (mediaUnresolved.length > 0) {
86
+ const resolutions = [];
87
+ for (const el of mediaUnresolved) {
88
+ if (!el.src)
89
+ continue;
90
+ const src = resolveMediaSrc(el.src, projectDir);
91
+ const fileDuration = await probeMediaDuration(src);
92
+ if (fileDuration <= 0)
93
+ continue;
94
+ const effectiveDuration = fileDuration - el.mediaStart;
95
+ const sourceDuration = effectiveDuration > 0 ? effectiveDuration : fileDuration;
96
+ resolutions.push({ id: el.id, duration: sourceDuration });
97
+ }
98
+ if (resolutions.length > 0) {
99
+ html = injectDurations(html, resolutions);
100
+ }
101
+ }
102
+ return clampProbedMedia(html, projectDir, probeMediaDuration);
103
+ }
104
+ async function clampProbedMedia(html, projectDir, probeMediaDuration) {
105
+ const preResolved = extractResolvedMedia(html);
106
+ const clampList = [];
107
+ for (const el of preResolved) {
108
+ if (!el.src)
109
+ continue;
110
+ if (el.loop)
111
+ continue;
112
+ const src = resolveMediaSrc(el.src, projectDir);
113
+ const fileDuration = await probeMediaDuration(src);
114
+ if (fileDuration <= 0)
115
+ continue;
116
+ const maxDuration = fileDuration - el.mediaStart;
117
+ if (maxDuration > 0 && shouldClampResolvedMediaDuration(el.tagName, el.duration, maxDuration)) {
118
+ clampList.push({ id: el.id, duration: maxDuration });
119
+ }
120
+ }
121
+ if (clampList.length > 0) {
122
+ html = clampDurations(html, clampList);
123
+ }
124
+ return html;
125
+ }
126
+
127
+ // ../core/dist/compiler/htmlBundler.js
128
+ import { createHash } from "crypto";
129
+
130
+ // ../core/dist/sceneParts.js
131
+ var SCENE_PART_ATTR = "data-hf-scene";
132
+ var SCENE_PARTS_META = "hf-scene-parts";
133
+ var SCENE_FONTS_ATTR = "data-hf-scene-fonts";
134
+ var SCENE_NO_SWAP_ATTR = "data-hf-scene-no-swap";
135
+
136
+ // ../core/dist/compiler/externalScripts.js
137
+ function readExternalScriptAttributes(el) {
138
+ const attributes = {};
139
+ if (el.hasAttribute("integrity"))
140
+ attributes.integrity = el.getAttribute("integrity") || "";
141
+ if (el.hasAttribute("crossorigin"))
142
+ attributes.crossorigin = el.getAttribute("crossorigin") || "";
143
+ if ((el.getAttribute("type") || "").trim().toLowerCase() === "module")
144
+ attributes.type = "module";
145
+ return attributes;
146
+ }
147
+ function ensureExternalScriptTag(doc, src, attributes = {}) {
148
+ const existing = [...doc.querySelectorAll("script[src]")].filter((el) => el.getAttribute("src")?.trim() === src);
149
+ const requirements = new Set([attributes.integrity, ...existing.map((el) => el.getAttribute("integrity"))].map((value) => value?.trim().replace(/(^|[\t\n\f\r ])(sha256|sha384|sha512)-/gi, (_match, space, algorithm) => `${space}${algorithm.toLowerCase()}-`)).filter((value) => Boolean(value)));
150
+ if (requirements.size > 1) {
151
+ throw new Error(`Conflicting script integrity requirements for ${src}`);
152
+ }
153
+ const integrity = [...requirements][0];
154
+ const elements = existing.length ? existing : [doc.createElement("script")];
155
+ for (const el of elements) {
156
+ if (integrity)
157
+ el.setAttribute("integrity", integrity);
158
+ if (attributes.crossorigin !== void 0)
159
+ el.setAttribute("crossorigin", attributes.crossorigin);
160
+ if (attributes.type)
161
+ el.setAttribute("type", attributes.type);
162
+ }
163
+ if (!existing.length) {
164
+ const el = elements[0];
165
+ el.setAttribute("src", src);
166
+ doc.body.appendChild(el);
167
+ }
168
+ }
169
+
170
+ // ../core/dist/compiler/importMaps.js
171
+ function isRecord(value) {
172
+ return typeof value === "object" && value !== null && !Array.isArray(value);
173
+ }
174
+ function isScopeMap(value) {
175
+ return isRecord(value) && Object.values(value).every(isRecord);
176
+ }
177
+ var rebaseEntries = (entries, rebase) => entries && Object.fromEntries(Object.entries(entries).map(([specifier, url]) => [
178
+ specifier,
179
+ typeof url === "string" ? rebase(url) : null
180
+ ]));
181
+ function parseImportMap(json, rebase) {
182
+ let parsed;
183
+ try {
184
+ parsed = JSON.parse(json);
185
+ } catch {
186
+ return null;
187
+ }
188
+ if (!isRecord(parsed))
189
+ return null;
190
+ const { imports, scopes } = parsed;
191
+ if (imports !== void 0 && !isRecord(imports))
192
+ return null;
193
+ if (scopes !== void 0 && !isScopeMap(scopes))
194
+ return null;
195
+ return {
196
+ imports: rebaseEntries(imports, rebase),
197
+ scopes: scopes && Object.fromEntries(Object.entries(scopes).map(([prefix, entries]) => [
198
+ rebase(prefix),
199
+ rebaseEntries(entries, rebase) ?? {}
200
+ ]))
201
+ };
202
+ }
203
+ function mergeEntries(into, from, where) {
204
+ for (const [specifier, url] of Object.entries(from ?? {})) {
205
+ if (!Object.hasOwn(into, specifier)) {
206
+ Object.defineProperty(into, specifier, {
207
+ value: url,
208
+ enumerable: true,
209
+ configurable: true,
210
+ writable: true
211
+ });
212
+ } else if (into[specifier] !== url) {
213
+ console.warn(`[Framey] import map conflict for "${specifier}"${where}: keeping ${into[specifier]}, ignoring ${url}.`);
214
+ }
215
+ }
216
+ }
217
+ function mergeImportMapsIntoDocument(doc, maps) {
218
+ if (maps.length === 0)
219
+ return;
220
+ let el = doc.querySelector('script[type="importmap"]');
221
+ let page = {};
222
+ try {
223
+ page = el ? JSON.parse(el.textContent || "{}") : {};
224
+ } catch {
225
+ console.warn("[Framey] the page's import map is not valid JSON; replacing it.");
226
+ }
227
+ const imports = { ...page.imports };
228
+ const scopes = { ...page.scopes };
229
+ for (const map of maps) {
230
+ mergeEntries(imports, map.imports, "");
231
+ for (const [prefix, entries] of Object.entries(map.scopes ?? {})) {
232
+ const scope = (Object.hasOwn(scopes, prefix) ? scopes[prefix] : void 0) ?? {};
233
+ Object.defineProperty(scopes, prefix, { value: scope, enumerable: true });
234
+ mergeEntries(scope, entries, ` in scope ${prefix}`);
235
+ }
236
+ }
237
+ if (!el) {
238
+ el = doc.createElement("script");
239
+ el.setAttribute("type", "importmap");
240
+ doc.head.prepend(el);
241
+ }
242
+ el.textContent = JSON.stringify({
243
+ ...page,
244
+ imports,
245
+ ...Object.keys(scopes).length ? { scopes } : {}
246
+ }).replace(/</g, "\\u003c");
247
+ }
248
+ function emitMountedModuleScripts(doc, importMaps, moduleScripts) {
249
+ mergeImportMapsIntoDocument(doc, importMaps);
250
+ for (const content of moduleScripts) {
251
+ const el = doc.createElement("script");
252
+ el.setAttribute("type", "module");
253
+ el.textContent = content;
254
+ doc.body.appendChild(el);
255
+ }
256
+ }
257
+
258
+ // ../core/dist/runtime/flattenedRoot.js
259
+ var FLATTENED_INNER_ROOT_STRIP_ATTRS = [
260
+ "data-composition-id",
261
+ "data-composition-file",
262
+ "data-start",
263
+ "data-duration",
264
+ "data-end",
265
+ "data-track-index",
266
+ "data-track",
267
+ "data-composition-src",
268
+ "data-hf-authored-duration",
269
+ "data-hf-authored-end"
270
+ ];
271
+ function markFlattenedInnerRoot(prepared) {
272
+ const authoredRootId = prepared.getAttribute("id")?.trim();
273
+ for (const attrName of FLATTENED_INNER_ROOT_STRIP_ATTRS) {
274
+ prepared.removeAttribute(attrName);
275
+ }
276
+ if (authoredRootId) {
277
+ prepared.removeAttribute("id");
278
+ prepared.setAttribute("data-hf-authored-id", authoredRootId);
279
+ }
280
+ prepared.setAttribute("data-hf-inner-root", "true");
281
+ }
282
+
283
+ // ../core/dist/runtime/applyVariableBindings.js
284
+ function sanitizeCssValue(value) {
285
+ return value.replace(/[;{}<>\r\n]/g, "");
286
+ }
287
+
288
+ // ../core/dist/compiler/htmlBundler.js
289
+ import { AsyncLocalStorage } from "async_hooks";
290
+ import { readFileSync, existsSync, statSync } from "fs";
291
+ import { parse as parseJs } from "acorn";
292
+ import { resolve as resolve2, relative, dirname, isAbsolute, sep } from "path";
293
+
294
+ // ../core/dist/compiler/standaloneEntry.js
295
+ function normalizeCompositionSrcPath(srcPath) {
296
+ return srcPath.replace(/\\/g, "/").replace(/^\.\//, "");
297
+ }
298
+ function readSceneRoot(entryHtml) {
299
+ if (!entryHtml)
300
+ return null;
301
+ const { document } = parseHTML(entryHtml);
302
+ const template = document.querySelector("template");
303
+ const scope = template ? parseHTML(template.innerHTML).document : document;
304
+ return scope.querySelector("[data-composition-id]");
305
+ }
306
+ function setSceneFxChain(el, sceneFxChain) {
307
+ if (sceneFxChain) {
308
+ el.setAttribute(HF_AUDIO_FX_ATTR, sceneFxChain);
309
+ } else {
310
+ el.removeAttribute(HF_AUDIO_FX_ATTR);
311
+ }
312
+ }
313
+ function createStandaloneEntryRenderClone(root, host, sceneDuration, sceneFxChain) {
314
+ const hostClone = host.cloneNode(true);
315
+ hostClone.setAttribute("data-start", "0");
316
+ if (root === host) {
317
+ setSceneFxChain(hostClone, sceneFxChain);
318
+ return hostClone;
319
+ }
320
+ const rootClone = root.cloneNode(false);
321
+ if (sceneDuration != null) {
322
+ rootClone.setAttribute("data-duration", sceneDuration);
323
+ } else {
324
+ rootClone.removeAttribute("data-duration");
325
+ }
326
+ setSceneFxChain(rootClone, sceneFxChain);
327
+ rootClone.appendChild(hostClone);
328
+ return rootClone;
329
+ }
330
+ function replaceBodyWithRenderClone(body, renderClone) {
331
+ const libraries = Array.from(body.children).filter((child) => child.tagName === "SCRIPT" && child.hasAttribute("src"));
332
+ while (body.firstChild) {
333
+ body.removeChild(body.firstChild);
334
+ }
335
+ for (const library of libraries)
336
+ body.appendChild(library);
337
+ body.appendChild(renderClone);
338
+ }
339
+ function extractStandaloneEntryFromIndex(indexHtml, entryFile, entryHtml) {
340
+ const normalizedEntryFile = normalizeCompositionSrcPath(entryFile);
341
+ const { document } = parseHTML(indexHtml);
342
+ const body = document.querySelector("body");
343
+ if (!body)
344
+ return null;
345
+ const hosts = Array.from(document.querySelectorAll("[data-composition-src]"));
346
+ const host = hosts.find((candidate) => normalizeCompositionSrcPath(candidate.getAttribute("data-composition-src") || "") === normalizedEntryFile);
347
+ if (!host)
348
+ return null;
349
+ const root = Array.from(body.children).find((candidate) => candidate.hasAttribute("data-composition-id")) ?? null;
350
+ if (!root)
351
+ return null;
352
+ const sceneRoot = readSceneRoot(entryHtml);
353
+ const sceneDuration = sceneRoot?.getAttribute("data-duration") ?? host.getAttribute("data-duration");
354
+ const sceneFxChain = sceneRoot?.getAttribute(HF_AUDIO_FX_ATTR) || null;
355
+ const renderClone = createStandaloneEntryRenderClone(root, host, sceneDuration, sceneFxChain);
356
+ replaceBodyWithRenderClone(body, renderClone);
357
+ return document.toString();
358
+ }
359
+
360
+ // ../core/dist/generated/svg-selector-aliases-inline.js
361
+ var SVG_SELECTOR_ALIASES_IIFE = '"use strict";(()=>{function I(e){return e?/[\\w-]/.test(e)||e.charCodeAt(0)>=128:!1}function _(e){return e===" "||e===" "||e===`\n`||e==="\\r"||e==="\\f"}var j=/^[0-9a-fA-F]{1,6}/;function G(e){let n=e>=55296&&e<=57343;return e===0||e>1114111||n?65533:e}function $(e,n){return e[n]==="\\r"&&e[n+1]===`\n`?n+2:_(e[n])?n+1:n}function R(e,n){let t=e[n+1];if(t===void 0||/[\\n\\r\\f]/.test(t))return null;let i=j.exec(e.slice(n+1,n+7));if(!i)return{value:t,end:n+2};let o=G(Number.parseInt(i[0],16));return{value:String.fromCodePoint(o),end:$(e,n+1+i[0].length)}}function H(e,n){let t=o=>I(o)&&!/[0-9-]/.test(o),i=o=>e[o]==="\\\\"&&R(e,o)!==null;return e[n]==="-"?e[n+1]==="-"||t(e[n+1])||i(n+1):t(e[n])||i(n)}function y(e,n){let t=n;for(;e.startsWith("/*",t);){let i=e.indexOf("*/",t+2);t=i<0?e.length:i+2}return t}function A(e,n){let t=y(e,n);for(;_(e[t]);)t=y(e,t+1);return t}function h(e,n){if(!H(e,n))return null;let t=n,i="";for(;t<e.length;){let o=e[t];if(o==="\\\\"){let a=R(e,t);if(!a)break;i+=a.value,t=a.end;continue}if(!I(o))break;i+=o,t+=1}return t===n?null:{value:i,end:t}}var C=45;function T(e){return e>=48&&e<=57}function z(e){return e>=128||e===C||e===95||T(e)||e>=65&&e<=90||e>=97&&e<=122}function J(e,n){let t=e.charCodeAt(n);return t>=1&&t<=31||t===127?!0:T(t)?n===0||n===1&&e.charCodeAt(0)===C:!1}function k(e){let n="";for(let t=0;t<e.length;t+=1){let i=e.charCodeAt(t),o=e[t];i===0?n+="\\uFFFD":J(e,t)?n+=`\\\\${i.toString(16)} `:t===0&&e.length===1&&i===C?n+=`\\\\${o}`:z(i)?n+=o:n+=`\\\\${o}`}return n}var W=/\\/\\*(?:[^*]|\\*(?!\\/))*\\*\\/|\\\\(?:[0-9a-fA-F]{1,6}(?:\\r\\n|[ \\t\\r\\n\\f])?|[\\s\\S])|"(?:[^"\\\\]|\\\\[\\s\\S])*"|\'(?:[^\'\\\\]|\\\\[\\s\\S])*\'|\\[(?:\\/\\*(?:[^*]|\\*(?!\\/))*\\*\\/|\\\\[\\s\\S]|"(?:[^"\\\\]|\\\\[\\s\\S])*"|\'(?:[^\'\\\\]|\\\\[\\s\\S])*\'|[^\\]"\'\\\\/]|\\/(?!\\*))*\\]/g;function Q(e){let n=new Array(e.length).fill(!0);for(let t of e.matchAll(W)){let i=t.index;n.fill(!1,i,i+t[0].length)}return n}function q(e,n,t){if(n.length===0||!e.includes("#"))return e;let i=new Set(n),o=Q(e),a="",u=0;for(;u<e.length;){let d=o[u]&&e[u]==="#"?h(e,u+1):null;d&&i.has(d.value)?(a+=t(d.value),u=d.end):(a+=e[u],u+=1)}return a}function X(e){let n="";for(let t=0;t<e.length;t+=1){if(e[t]==="\\\\"){let i=e[t+1];if(i!==void 0&&/[\\n\\r\\f]/.test(i)){t=$(e,t+1)-1;continue}let o=R(e,t);if(o){n+=o.value,t=o.end-1;continue}}n+=e[t]}return n}function N(e){return Array.from(e,n=>{let t=n.charCodeAt(0);return t===0?"\\uFFFD":t<32||t===127?`\\\\${t.toString(16)} `:n===\'"\'||n==="\\\\"?`\\\\${n}`:n}).join("")}function Y(e,n){return e?{kind:"any"}:n===void 0?{kind:"none"}:{kind:"named",prefix:n}}function Z(e,n){return e[n]==="|"&&e[n+1]!=="="}function B(e,n){let t=e[n]==="*",i=t?{value:"*",end:n+1}:h(e,n),o=y(e,i?.end??n);if(!Z(e,o))return t?null:i?{token:i,namespace:{kind:"none"}}:null;let a=h(e,y(e,o+1));return a?{token:a,namespace:Y(t,i?.value)}:null}function K(e){if(e[0]!=="[")return null;let n=A(e,1),t=B(e,n);if(!t)return null;let{token:i,namespace:o}=t;return{name:i.value,rawName:e.slice(n,i.end),namespace:o,end:i.end}}function ee(e,n){let t=/^(?:"((?:\\\\[\\s\\S]|[^"\\\\])*)"|\'((?:\\\\[\\s\\S]|[^\'\\\\])*)\')/.exec(e.slice(n));return t?{value:X(t[1]??t[2]),end:n+t[0].length}:h(e,n)}function ne(e,n){let t=A(e,n),i=h(e,t);if(i){if(!/^[is]$/i.test(i.value))return null;t=A(e,i.end)}return e[t]!=="]"||t!==e.length-1?null:{flag:i?.value}}function F(e){let n=K(e);if(!n)return null;let t=A(e,n.end),o=["=","~=","|=","^=","$=","*="].find(d=>e.startsWith(d,t));if(!o)return null;let a=ee(e,A(e,t+o.length));if(!a)return null;let u=ne(e,a.end);return u?{name:n.name,rawName:n.rawName,namespace:n.namespace,operator:o,value:a.value,flag:u.flag}:null}function E(e,n){return e.replace(W,t=>t.startsWith("[")?n(t):t)}var re="data-hf-svg-reference-aliases";function O(e,n,t,i){let o={"=":(s,r)=>s===r,"~=":(s,r)=>s.split(/[ \\t\\r\\n\\f]+/).includes(r),"|=":(s,r)=>s===r||s.startsWith(r+"-"),"^=":(s,r)=>s.startsWith(r),"$=":(s,r)=>s.endsWith(r),"*=":(s,r)=>s.includes(r)},a=(s,r,l)=>!r&&l!=="="&&l!=="|="?!1:o[l](s,r),u=s=>s.replace(/[A-Z]/g,r=>r.toLowerCase()),d=s=>{let r=F(s);if(!r)return s;let{name:l,rawName:g,namespace:m,operator:b,value:D,flag:w}=r;if(m.kind==="named"!=(i!==void 0))return s;let x=w?.toLowerCase()==="i"?u:S=>S,L=u(l),P=t.filter(S=>{let V=m.kind==="none"?S.name:S.localName,U=m.kind==="named"?i.get(m.prefix):null;return(m.kind==="any"||S.namespaceURI===U)&&u(V)===L}),v=new Set([s]);for(let S of P)a(x(S.before),x(D),b)&&v.add(`[${g}="${N(S.after)}"${w?` ${w}`:""}]`);return v.size===1?s:`:is(${[...v].join(", ")})`};if(i)return E(e,d);let p=new Map(n.map(({id:s,replacement:r})=>[s,r])),f=new Map;for(let s of t){if(s.name!=="id"||s.before===s.after||p.has(s.before))continue;let r=f.get(s.before);r||(r=new Set([`#${k(s.before)}`]),f.set(s.before,r)),r.add(`#${k(s.after)}`)}for(let[s,r]of f)p.set(s,`:is(${[...r].join(", ")})`);let c=q(e,[...p.keys()],s=>p.get(s));return E(c,d)}function se(e,n,t=!0){let i=[],a=(t?[...e.querySelectorAll(`[${n}]`)]:[]).map(d=>d.getAttribute(n)),u=e.getAttribute?.(n);u&&a.unshift(u);for(let d of a){let p;try{p=JSON.parse(d)}catch{continue}if(!Array.isArray(p))continue;let f=p;for(let c of f){if(!ie(c))continue;let{name:s,localName:r,namespaceURI:l,before:g,after:m}=c;i.push({name:s,localName:r,namespaceURI:l,before:g,after:m})}}return i}function ie(e){if(!e||typeof e!="object")return!1;let{name:n,localName:t,namespaceURI:i,before:o,after:a}=e;return typeof n=="string"&&typeof t=="string"&&(i===null||typeof i=="string")&&typeof o=="string"&&typeof a=="string"}function oe(e){let n=[],t=[],i=!1,o,a=new WeakMap,u=(f,c)=>{for(let s of f){if("selectorText"in s){let r=s,l=a.get(r),g=r.selectorText,m=l?.applied===g?l.authored:g,b=O(m,[],t,c);b!==g&&(r.selectorText=b),b===m?a.delete(r):a.set(r,{authored:m,applied:r.selectorText})}"cssRules"in s&&u(s.cssRules,c)}},d=()=>{if(t.length)for(let f of e.document.styleSheets){let c;try{c=f.cssRules}catch{continue}let s=new Map;for(let r of c){if(!("namespaceURI"in r))continue;let{prefix:l,namespaceURI:g}=r;l&&s.set(l,g||null)}s.size&&u(c,s)}},p={rewrite:(f,c=[])=>{if(typeof f!="string"||!f.includes("#")&&!f.includes("["))return f;let s=O(f,c.length?[...c,...n]:n,t);if(s!==f){if(!o){let r=e.document.createElement("div");o=r.matches.bind(r)}o(f)}return s},refresh(){t=se(e.document,re).filter(r=>r.before!==r.after);let f=new Set(t.filter(r=>r.name==="id").map(r=>r.before)),c=new Set;n=[];for(let r of e.document.querySelectorAll("[data-hf-authored-id][id]")){let l=r.getAttribute("data-hf-authored-id");if(!l||l===r.id||c.has(l)||f.has(l))continue;c.add(l);let g=N(l);n.push({id:l,replacement:`:is(#${k(l)}, [data-hf-authored-id="${g}"])`})}if(d(),i||!n.length&&!t.length)return;let s=e.Element.prototype;s.querySelector=new Proxy(s.querySelector,{apply(r,l,g){return Reflect.apply(r,l,[p.rewrite(g[0])])}}),s.querySelectorAll=new Proxy(s.querySelectorAll,{apply(r,l,g){return Reflect.apply(r,l,[p.rewrite(g[0])])}}),i=!0}};e.__hfSvgSelectorAliases=p,p.refresh()}function M(){let e=window;e.__hfSvgSelectorAliases||oe(e)}M();})();\n';
362
+ function getSvgSelectorAliasesScript() {
363
+ return SVG_SELECTOR_ALIASES_IIFE;
364
+ }
365
+
366
+ // ../core/dist/compiler/compositionScoping.js
367
+ import postcss from "postcss";
368
+
369
+ // ../core/dist/compiler/selectorIdTokens.js
370
+ function isNameChar(char) {
371
+ if (!char)
372
+ return false;
373
+ return /[\w-]/.test(char) || char.charCodeAt(0) >= 128;
374
+ }
375
+ function isCssWhitespace(char) {
376
+ return char === " " || char === " " || char === "\n" || char === "\r" || char === "\f";
377
+ }
378
+ var HEX_ESCAPE_RE = /^[0-9a-fA-F]{1,6}/;
379
+ function sanitizeCodePoint(codePoint) {
380
+ const isSurrogate = codePoint >= 55296 && codePoint <= 57343;
381
+ return codePoint === 0 || codePoint > 1114111 || isSurrogate ? 65533 : codePoint;
382
+ }
383
+ function skipEscapeWhitespace(text, index) {
384
+ if (text[index] === "\r" && text[index + 1] === "\n")
385
+ return index + 2;
386
+ return isCssWhitespace(text[index]) ? index + 1 : index;
387
+ }
388
+ function consumeCssEscape(text, index) {
389
+ const next = text[index + 1];
390
+ if (next === void 0 || /[\n\r\f]/.test(next))
391
+ return null;
392
+ const hex = HEX_ESCAPE_RE.exec(text.slice(index + 1, index + 7));
393
+ if (!hex)
394
+ return { value: next, end: index + 2 };
395
+ const codePoint = sanitizeCodePoint(Number.parseInt(hex[0], 16));
396
+ return {
397
+ value: String.fromCodePoint(codePoint),
398
+ end: skipEscapeWhitespace(text, index + 1 + hex[0].length)
399
+ };
400
+ }
401
+ function startsCssIdentifier(text, start) {
402
+ const isStart = (char) => isNameChar(char) && !/[0-9-]/.test(char);
403
+ const escape = (index) => text[index] === "\\" && consumeCssEscape(text, index) !== null;
404
+ if (text[start] === "-")
405
+ return text[start + 1] === "-" || isStart(text[start + 1]) || escape(start + 1);
406
+ return isStart(text[start]) || escape(start);
407
+ }
408
+ function skipCssComments(text, start) {
409
+ let index = start;
410
+ while (text.startsWith("/*", index)) {
411
+ const end = text.indexOf("*/", index + 2);
412
+ index = end < 0 ? text.length : end + 2;
413
+ }
414
+ return index;
415
+ }
416
+ function skipCssTrivia(text, start) {
417
+ let index = skipCssComments(text, start);
418
+ while (isCssWhitespace(text[index]))
419
+ index = skipCssComments(text, index + 1);
420
+ return index;
421
+ }
422
+ function decodeCssIdentifierAt(text, start) {
423
+ if (!startsCssIdentifier(text, start))
424
+ return null;
425
+ let index = start;
426
+ let value = "";
427
+ while (index < text.length) {
428
+ const char = text[index];
429
+ if (char === "\\") {
430
+ const escape = consumeCssEscape(text, index);
431
+ if (!escape)
432
+ break;
433
+ value += escape.value;
434
+ index = escape.end;
435
+ continue;
436
+ }
437
+ if (!isNameChar(char))
438
+ break;
439
+ value += char;
440
+ index += 1;
441
+ }
442
+ return index === start ? null : { value, end: index };
443
+ }
444
+ var CODE_UNIT_HYPHEN = 45;
445
+ function isDigitCodeUnit(codeUnit) {
446
+ return codeUnit >= 48 && codeUnit <= 57;
447
+ }
448
+ function isPlainNameCodeUnit(codeUnit) {
449
+ return codeUnit >= 128 || codeUnit === CODE_UNIT_HYPHEN || codeUnit === 95 || isDigitCodeUnit(codeUnit) || codeUnit >= 65 && codeUnit <= 90 || codeUnit >= 97 && codeUnit <= 122;
450
+ }
451
+ function needsHexEscape(value, index) {
452
+ const codeUnit = value.charCodeAt(index);
453
+ if (codeUnit >= 1 && codeUnit <= 31 || codeUnit === 127)
454
+ return true;
455
+ if (!isDigitCodeUnit(codeUnit))
456
+ return false;
457
+ return index === 0 || index === 1 && value.charCodeAt(0) === CODE_UNIT_HYPHEN;
458
+ }
459
+ function escapeCssIdentifier(value) {
460
+ let result = "";
461
+ for (let index = 0; index < value.length; index += 1) {
462
+ const codeUnit = value.charCodeAt(index);
463
+ const char = value[index];
464
+ if (codeUnit === 0)
465
+ result += "\uFFFD";
466
+ else if (needsHexEscape(value, index))
467
+ result += `\\${codeUnit.toString(16)} `;
468
+ else if (index === 0 && value.length === 1 && codeUnit === CODE_UNIT_HYPHEN)
469
+ result += `\\${char}`;
470
+ else if (isPlainNameCodeUnit(codeUnit))
471
+ result += char;
472
+ else
473
+ result += `\\${char}`;
474
+ }
475
+ return result;
476
+ }
477
+ var GUARDED_SELECTOR_SEGMENT_RE = /\/\*(?:[^*]|\*(?!\/))*\*\/|\\(?:[0-9a-fA-F]{1,6}(?:\r\n|[ \t\r\n\f])?|[\s\S])|"(?:[^"\\]|\\[\s\S])*"|'(?:[^'\\]|\\[\s\S])*'|\[(?:\/\*(?:[^*]|\*(?!\/))*\*\/|\\[\s\S]|"(?:[^"\\]|\\[\s\S])*"|'(?:[^'\\]|\\[\s\S])*'|[^\]"'\\/]|\/(?!\*))*\]/g;
478
+ function markUnguardedOffsets(selector) {
479
+ const mask = new Array(selector.length).fill(true);
480
+ for (const match of selector.matchAll(GUARDED_SELECTOR_SEGMENT_RE)) {
481
+ const start = match.index;
482
+ mask.fill(false, start, start + match[0].length);
483
+ }
484
+ return mask;
485
+ }
486
+ function replaceSelectorIdTokens(selector, candidateIds, resolveReplacement) {
487
+ if (candidateIds.length === 0 || !selector.includes("#"))
488
+ return selector;
489
+ const candidates = new Set(candidateIds);
490
+ const unguarded = markUnguardedOffsets(selector);
491
+ let result = "";
492
+ let index = 0;
493
+ while (index < selector.length) {
494
+ const token = unguarded[index] && selector[index] === "#" ? decodeCssIdentifierAt(selector, index + 1) : null;
495
+ if (token && candidates.has(token.value)) {
496
+ result += resolveReplacement(token.value);
497
+ index = token.end;
498
+ } else {
499
+ result += selector[index];
500
+ index += 1;
501
+ }
502
+ }
503
+ return result;
504
+ }
505
+ function decodeCssString(value) {
506
+ let result = "";
507
+ for (let index = 0; index < value.length; index += 1) {
508
+ if (value[index] === "\\") {
509
+ const next = value[index + 1];
510
+ if (next !== void 0 && /[\n\r\f]/.test(next)) {
511
+ index = skipEscapeWhitespace(value, index + 1) - 1;
512
+ continue;
513
+ }
514
+ const escaped = consumeCssEscape(value, index);
515
+ if (escaped) {
516
+ result += escaped.value;
517
+ index = escaped.end - 1;
518
+ continue;
519
+ }
520
+ }
521
+ result += value[index];
522
+ }
523
+ return result;
524
+ }
525
+ function escapeCssAttributeValue(value) {
526
+ return Array.from(value, (char) => {
527
+ const code = char.charCodeAt(0);
528
+ if (code === 0)
529
+ return "\uFFFD";
530
+ if (code < 32 || code === 127)
531
+ return `\\${code.toString(16)} `;
532
+ return char === '"' || char === "\\" ? `\\${char}` : char;
533
+ }).join("");
534
+ }
535
+ function attributeNamespace(wildcard, prefix) {
536
+ if (wildcard)
537
+ return { kind: "any" };
538
+ return prefix === void 0 ? { kind: "none" } : { kind: "named", prefix };
539
+ }
540
+ function isNamespaceSeparator(text, offset) {
541
+ return text[offset] === "|" && text[offset + 1] !== "=";
542
+ }
543
+ function readQualifiedAttributeName(text, start) {
544
+ const wildcard = text[start] === "*";
545
+ const first = wildcard ? { value: "*", end: start + 1 } : decodeCssIdentifierAt(text, start);
546
+ const separator = skipCssComments(text, first?.end ?? start);
547
+ if (!isNamespaceSeparator(text, separator)) {
548
+ if (wildcard)
549
+ return null;
550
+ return first ? { token: first, namespace: { kind: "none" } } : null;
551
+ }
552
+ const token = decodeCssIdentifierAt(text, skipCssComments(text, separator + 1));
553
+ if (!token)
554
+ return null;
555
+ return { token, namespace: attributeNamespace(wildcard, first?.value) };
556
+ }
557
+ function readAttributeName(predicate) {
558
+ if (predicate[0] !== "[")
559
+ return null;
560
+ const start = skipCssTrivia(predicate, 1);
561
+ const qualified = readQualifiedAttributeName(predicate, start);
562
+ if (!qualified)
563
+ return null;
564
+ const { token, namespace } = qualified;
565
+ return {
566
+ name: token.value,
567
+ rawName: predicate.slice(start, token.end),
568
+ namespace,
569
+ end: token.end
570
+ };
571
+ }
572
+ function readAttributeValue(predicate, start) {
573
+ const quoted = /^(?:"((?:\\[\s\S]|[^"\\])*)"|'((?:\\[\s\S]|[^'\\])*)')/.exec(predicate.slice(start));
574
+ if (quoted)
575
+ return { value: decodeCssString(quoted[1] ?? quoted[2]), end: start + quoted[0].length };
576
+ return decodeCssIdentifierAt(predicate, start);
577
+ }
578
+ function readAttributeEnding(predicate, start) {
579
+ let offset = skipCssTrivia(predicate, start);
580
+ const token = decodeCssIdentifierAt(predicate, offset);
581
+ if (token) {
582
+ if (!/^[is]$/i.test(token.value))
583
+ return null;
584
+ offset = skipCssTrivia(predicate, token.end);
585
+ }
586
+ if (predicate[offset] !== "]" || offset !== predicate.length - 1)
587
+ return null;
588
+ return { flag: token?.value };
589
+ }
590
+ function parseAttributeSelector(predicate) {
591
+ const name = readAttributeName(predicate);
592
+ if (!name)
593
+ return null;
594
+ const offset = skipCssTrivia(predicate, name.end);
595
+ const operators = ["=", "~=", "|=", "^=", "$=", "*="];
596
+ const operator = operators.find((candidate) => predicate.startsWith(candidate, offset));
597
+ if (!operator)
598
+ return null;
599
+ const value = readAttributeValue(predicate, skipCssTrivia(predicate, offset + operator.length));
600
+ if (!value)
601
+ return null;
602
+ const ending = readAttributeEnding(predicate, value.end);
603
+ if (!ending)
604
+ return null;
605
+ return {
606
+ name: name.name,
607
+ rawName: name.rawName,
608
+ namespace: name.namespace,
609
+ operator,
610
+ value: value.value,
611
+ flag: ending.flag
612
+ };
613
+ }
614
+ function replaceSelectorAttributeTokens(selector, rewrite) {
615
+ return selector.replace(GUARDED_SELECTOR_SEGMENT_RE, (segment) => segment.startsWith("[") ? rewrite(segment) : segment);
616
+ }
617
+
618
+ // ../core/dist/compiler/compositionScoping.js
619
+ var AUTHORED_ROOT_ID_ATTR = "data-hf-authored-id";
620
+ var INNER_ROOT_ATTR = "data-hf-inner-root";
621
+ function escapeRegExp(value) {
622
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
623
+ }
624
+ function escapeCssAttributeValue2(value) {
625
+ return value.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
626
+ }
627
+ function getAuthoredRootIdSelectorForms(authoredRootId) {
628
+ const trimmed = authoredRootId.trim();
629
+ if (!trimmed)
630
+ return [];
631
+ return Array.from(/* @__PURE__ */ new Set([trimmed, escapeCssIdentifier(trimmed)])).filter(Boolean);
632
+ }
633
+ function replaceAuthoredRootIdSelectors(selector, authoredRootId, replacement) {
634
+ const forms = getAuthoredRootIdSelectorForms(authoredRootId);
635
+ return replaceSelectorIdTokens(selector, forms, () => replacement);
636
+ }
637
+ function normalizeAuthoredRootIdSelector(selector, authoredRootId) {
638
+ const trimmed = authoredRootId?.trim();
639
+ if (!trimmed)
640
+ return selector;
641
+ return replaceAuthoredRootIdSelectors(selector, trimmed, `[${AUTHORED_ROOT_ID_ATTR}="${escapeCssAttributeValue2(trimmed)}"]`);
642
+ }
643
+ function compositionBoxSelector(scope) {
644
+ return `${scope}:not(:has([${INNER_ROOT_ATTR}])), ${scope} > [${INNER_ROOT_ATTR}]`;
645
+ }
646
+ function scopeSelector(selector, scope, compositionId, authoredRootId, compoundAuthoredRoot, scopeRootSelectors) {
647
+ const selectorWithoutAuthoredRootId = normalizeAuthoredRootIdSelector(selector, authoredRootId);
648
+ const selectorWithoutRootTiming = normalizeCompositionRootSelector(selectorWithoutAuthoredRootId, scope, compositionId);
649
+ const trimmed = selectorWithoutRootTiming.trim();
650
+ if (!trimmed)
651
+ return selector;
652
+ if (trimmed === "*")
653
+ return selector;
654
+ if (/^(html|body|:root)$/i.test(trimmed)) {
655
+ return scopeRootSelectors ? compositionBoxSelector(scope) : selector;
656
+ }
657
+ const compositionIdPattern = new RegExp(`\\[\\s*data-composition-id\\s*[\\^\\*\\$]?=\\s*(["'])${escapeRegExp(compositionId)}\\1\\s*\\]`, "g");
658
+ if (compositionIdPattern.test(trimmed)) {
659
+ const isRootBoxSelector = trimmed.replace(compositionIdPattern, "").trim() === "";
660
+ if (isRootBoxSelector) {
661
+ return compositionBoxSelector(scope);
662
+ }
663
+ return selectorWithoutRootTiming.replace(compositionIdPattern, scope);
664
+ }
665
+ const leading = selectorWithoutRootTiming.match(/^\s*/)?.[0] ?? "";
666
+ const trailing = selectorWithoutRootTiming.match(/\s*$/)?.[0] ?? "";
667
+ if (compoundAuthoredRoot) {
668
+ const authoredRootAttr = authoredRootId ? `[${AUTHORED_ROOT_ID_ATTR}="${escapeCssAttributeValue2(authoredRootId)}"]` : null;
669
+ if (authoredRootAttr && trimmed.startsWith(authoredRootAttr)) {
670
+ const rest = trimmed.slice(authoredRootAttr.length);
671
+ return `${leading}${scope}${authoredRootAttr}${rest}${trailing}`;
672
+ }
673
+ }
674
+ return `${leading}${scope} ${trimmed}${trailing}`;
675
+ }
676
+ function normalizeCompositionRootSelector(selector, scope, compositionId) {
677
+ const quotedCompId = escapeRegExp(compositionId);
678
+ const compAttr = String.raw`\[\s*data-composition-id\s*=\s*(?:"${quotedCompId}"|'${quotedCompId}')\s*\]`;
679
+ const timingAttr = String.raw`\s*\[\s*data-(?:start|duration)\s*=\s*(?:"[^"]*"|'[^']*')\s*\]`;
680
+ return selector.replace(new RegExp(`${compAttr}(?:${timingAttr})+`, "g"), scope).replace(new RegExp(`(?:${timingAttr})+${compAttr}`, "g"), scope);
681
+ }
682
+ var GLOBAL_AT_RULES = /* @__PURE__ */ new Set(["keyframes", "-webkit-keyframes", "font-face"]);
683
+ function isAtRuleNode(node) {
684
+ return node?.type === "atrule";
685
+ }
686
+ function isInsideGlobalAtRule(rule) {
687
+ let current = rule.parent;
688
+ while (current) {
689
+ if (isAtRuleNode(current) && GLOBAL_AT_RULES.has(current.name.toLowerCase())) {
690
+ return true;
691
+ }
692
+ current = current.parent;
693
+ }
694
+ return false;
695
+ }
696
+ function isNestedInsideAnotherRule(rule) {
697
+ let current = rule.parent;
698
+ while (current) {
699
+ if (current.type === "rule")
700
+ return true;
701
+ current = current.parent;
702
+ }
703
+ return false;
704
+ }
705
+ function scopeCssToComposition(css, compositionId, scopeSelectorOverride, authoredRootId, options) {
706
+ const trimmedCompositionId = compositionId.trim();
707
+ if (!css || !trimmedCompositionId)
708
+ return css;
709
+ const scope = scopeSelectorOverride || `[data-composition-id="${escapeCssAttributeValue2(trimmedCompositionId)}"]`;
710
+ const root = parseCss(css);
711
+ return root ? scopeParsedCss(root, scope, trimmedCompositionId, authoredRootId, options) : "";
712
+ }
713
+ function parseCss(css) {
714
+ try {
715
+ return postcss.parse(css);
716
+ } catch {
717
+ return null;
718
+ }
719
+ }
720
+ function forEachScopedRule(root, visit) {
721
+ root.walkRules((rule) => {
722
+ if (isInsideGlobalAtRule(rule))
723
+ return;
724
+ if (isNestedInsideAnotherRule(rule))
725
+ return;
726
+ visit(rule);
727
+ });
728
+ }
729
+ function scopeParsedCss(root, scope, compositionId, authoredRootId, options) {
730
+ forEachScopedRule(root, (rule) => {
731
+ rule.selectors = rule.selectors.map((selector) => scopeSelector(selector, scope, compositionId, authoredRootId, options?.compoundAuthoredRoot, options?.scopeRootSelectors));
732
+ });
733
+ return root.toResult({ map: false }).css;
734
+ }
735
+ var PLACEHOLDER_ID = "hf-scope-placeholder";
736
+ var PLACEHOLDER_SCOPE = `[data-composition-id="${PLACEHOLDER_ID}"]`;
737
+ var PLAIN_ID = /^[\w.:-]+$/;
738
+ var PLAIN_SCOPE = /^\[data-composition-id="([\w.:-]+)"\]$/;
739
+ function createCompositionCssScoper() {
740
+ const templates = /* @__PURE__ */ new Map();
741
+ return (css, compositionId, scopeSelectorOverride, authoredRootId, options) => {
742
+ const trimmedId = compositionId.trim();
743
+ const scope = scopeSelectorOverride ?? "";
744
+ const scopeId = PLAIN_SCOPE.exec(scope)?.[1];
745
+ if (!scopeId || scopeId === trimmedId || !PLAIN_ID.test(trimmedId) || trimmedId === PLACEHOLDER_ID)
746
+ return scopeCssToComposition(css, compositionId, scopeSelectorOverride, authoredRootId, options);
747
+ const key = JSON.stringify([
748
+ trimmedId,
749
+ authoredRootId ?? null,
750
+ Boolean(options?.compoundAuthoredRoot),
751
+ Boolean(options?.scopeRootSelectors),
752
+ css
753
+ ]);
754
+ let template = templates.get(key);
755
+ if (template === void 0) {
756
+ template = scopeTemplate(css, trimmedId, authoredRootId, options);
757
+ templates.set(key, template);
758
+ }
759
+ return template === null ? scopeCssToComposition(css, compositionId, scopeSelectorOverride, authoredRootId, options) : template.split(PLACEHOLDER_SCOPE).join(scope);
760
+ };
761
+ }
762
+ function scopeTemplate(css, compositionId, authoredRootId, options) {
763
+ if (css.includes(PLACEHOLDER_SCOPE))
764
+ return null;
765
+ if (!css)
766
+ return css;
767
+ const root = parseCss(css);
768
+ if (!root)
769
+ return "";
770
+ let rawSelector = false;
771
+ forEachScopedRule(root, (rule) => {
772
+ rawSelector ||= Boolean(rule.raws.selector);
773
+ });
774
+ return rawSelector ? null : scopeParsedCss(root, PLACEHOLDER_SCOPE, compositionId, authoredRootId, options);
775
+ }
776
+ function isFontFaceAtRule(node) {
777
+ return node.type === "atrule" && node.name.toLowerCase() === "font-face";
778
+ }
779
+ function fontFaceKey(atRule) {
780
+ const decls = [];
781
+ atRule.walkDecls((decl) => {
782
+ const value = decl.value.replace(/("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*')|\s+/g, (_m, str) => str ?? " ");
783
+ decls.push(`${decl.prop.trim().toLowerCase()}:${value.trim()}${decl.important ? "!important" : ""}`);
784
+ });
785
+ return decls.join(";");
786
+ }
787
+ var dedupeFontFaceRules = (styleTexts) => dropFontFaces(styleTexts);
788
+ function hoistFontFaceRules(styleTexts) {
789
+ const faces = [];
790
+ return { styles: dropFontFaces(styleTexts, faces), faces };
791
+ }
792
+ function dropFontFaces(styleTexts, hoisted) {
793
+ const seen = /* @__PURE__ */ new Set();
794
+ return [...styleTexts].reverse().map((css) => {
795
+ if (!css || !/@font-face/i.test(css))
796
+ return css;
797
+ let root;
798
+ try {
799
+ root = postcss.parse(css);
800
+ } catch {
801
+ return css;
802
+ }
803
+ let changed = false;
804
+ for (const node of [...root.nodes ?? []].reverse()) {
805
+ if (!isFontFaceAtRule(node))
806
+ continue;
807
+ const key = fontFaceKey(node);
808
+ if (!seen.has(key)) {
809
+ seen.add(key);
810
+ if (!hoisted)
811
+ continue;
812
+ hoisted.unshift(node.toString());
813
+ }
814
+ node.remove();
815
+ changed = true;
816
+ }
817
+ return changed ? root.toResult({ map: false }).css : css;
818
+ }).reverse();
819
+ }
820
+ function jsonScriptLiteral(value) {
821
+ return JSON.stringify(value).replace(/</g, "\\u003c");
822
+ }
823
+ var SCOPED_HYPERFRAMES_EXPRESSION = `!__hfBaseHyperframes
824
+ ? __hfBaseHyperframes
825
+ : Object.assign({}, __hfBaseHyperframes, {
826
+ assetUrl: function(path) {
827
+ var page = window.document.baseURI;
828
+ return new URL(path, __hfCompositionSrc ? new URL(__hfCompositionSrc, page) : page).href;
829
+ },
830
+ getVariables: function() {
831
+ var byComp = window.__hfVariablesByComp;
832
+ var scoped = byComp && __hfTimelineCompId ? byComp[__hfTimelineCompId] : null;
833
+ return scoped ? Object.assign({}, scoped) : {};
834
+ },
835
+ })`;
836
+ function scopedModulePrelude(timelineCompositionId, compositionSrc) {
837
+ return `const __hyperframes = (function(__hfBaseHyperframes, __hfTimelineCompId, __hfCompositionSrc) {
838
+ return ${SCOPED_HYPERFRAMES_EXPRESSION};
839
+ })(window.__hyperframes, ${jsonScriptLiteral(timelineCompositionId)}, ${jsonScriptLiteral(compositionSrc?.trim() || null)});
840
+ ${wrapScopedCompositionScript("", timelineCompositionId)}
841
+ `;
842
+ }
843
+ function wrapScopedCompositionScript(source, compositionId, errorLabel = "[Framey] composition script error:", scopeSelectorOverride, timelineCompositionId = compositionId, authoredRootId, compositionSrc) {
844
+ const compositionIdLiteral = jsonScriptLiteral(compositionId);
845
+ const timelineCompositionIdLiteral = jsonScriptLiteral(timelineCompositionId);
846
+ const errorLabelLiteral = jsonScriptLiteral(errorLabel);
847
+ const escapedCompositionId = escapeRegExp(compositionId);
848
+ const authoredRootIdLiteral = jsonScriptLiteral(authoredRootId?.trim() || null);
849
+ const scopeSelectorLiteral = jsonScriptLiteral(scopeSelectorOverride ?? null);
850
+ const rootSelectorPatternLiteral = jsonScriptLiteral(String.raw`\[\s*data-composition-id\s*=\s*(?:"${escapedCompositionId}"|'${escapedCompositionId}')\s*\]`);
851
+ const timingSelectorPatternLiteral = jsonScriptLiteral(String.raw`\s*\[\s*data-(?:start|duration)\s*=\s*(?:"[^"]*"|'[^']*')\s*\]`);
852
+ const aliasInstallerOutsideAuthoredStrictness = `(function(){ ${getSvgSelectorAliasesScript()} })();`;
853
+ return `(function(){
854
+ ${aliasInstallerOutsideAuthoredStrictness}
855
+ var __hfCompId = ${compositionIdLiteral};
856
+ var __hfTimelineCompId = ${timelineCompositionIdLiteral};
857
+ var __hfErrorLabel = ${errorLabelLiteral};
858
+ var __hfAuthoredRootId = ${authoredRootIdLiteral};
859
+ var __hfCompositionSrc = ${jsonScriptLiteral(compositionSrc?.trim() || null)};
860
+ var __hfAuthoredRootAttr = ${jsonScriptLiteral(AUTHORED_ROOT_ID_ATTR)};
861
+ var __hfEscapeAttr = function(value) {
862
+ return (value + "").replace(/\\\\/g, "\\\\\\\\").replace(/"/g, "\\\\\\"");
863
+ };
864
+ var __hfRootSelector = ${scopeSelectorLiteral} || (__hfCompId
865
+ ? '[data-composition-id="' + __hfEscapeAttr(__hfCompId) + '"]'
866
+ : "");
867
+ var __hfRoot = null;
868
+ var __hfRootSelectorPattern = ${rootSelectorPatternLiteral};
869
+ var __hfTimingSelectorPattern = ${timingSelectorPatternLiteral};
870
+ var __hfAuthoredRootSelector = __hfAuthoredRootId
871
+ ? "[" + __hfAuthoredRootAttr + '="' + __hfEscapeAttr(__hfAuthoredRootId) + '"]'
872
+ : "";
873
+ var __hfAuthoredRootEntries = __hfAuthoredRootSelector
874
+ ? [{ id: __hfAuthoredRootId, replacement: __hfAuthoredRootSelector }]
875
+ : [];
876
+ var __hfNormalizeSelector = function(selector) {
877
+ if (!__hfCompId || typeof selector !== "string") return selector;
878
+ var normalized = selector
879
+ .replace(new RegExp(__hfRootSelectorPattern + '(?:' + __hfTimingSelectorPattern + ')+', 'g'), __hfRootSelector)
880
+ .replace(new RegExp('(?:' + __hfTimingSelectorPattern + ')+' + __hfRootSelectorPattern, 'g'), __hfRootSelector);
881
+ return window.__hfSvgSelectorAliases.rewrite(normalized, __hfAuthoredRootEntries);
882
+ };
883
+ var __hfFindRoot = function() {
884
+ if (!__hfRoot && __hfRootSelector) {
885
+ __hfRoot = window.document.querySelector(__hfRootSelector);
886
+ }
887
+ return __hfRoot;
888
+ };
889
+ var __hfContains = function(node) {
890
+ var root = __hfFindRoot();
891
+ return !root || node === root || root.contains(node);
892
+ };
893
+ var __hfQueryAll = function(selector) {
894
+ var root = __hfFindRoot();
895
+ if (!root || typeof selector !== "string") {
896
+ return window.document.querySelectorAll(selector);
897
+ }
898
+ return Array.prototype.filter.call(window.document.querySelectorAll(__hfNormalizeSelector(selector)), function(node) {
899
+ return __hfContains(node);
900
+ });
901
+ };
902
+ var __hfQueryOne = function(selector) {
903
+ var matches = __hfQueryAll(selector);
904
+ return matches[0] || null;
905
+ };
906
+ var __hfGetElementById = function(id) {
907
+ var found = window.document.getElementById(id);
908
+ if (found && __hfContains(found)) return found;
909
+ var root = __hfFindRoot();
910
+ if (!root) return found || null;
911
+ var idValue = id + "";
912
+ if (__hfAuthoredRootId && __hfAuthoredRootId === idValue && root.getAttribute && root.getAttribute(__hfAuthoredRootAttr) === idValue) {
913
+ return root;
914
+ }
915
+ if (root.id === idValue) return root;
916
+ if (typeof root.querySelector !== "function") return null;
917
+ try {
918
+ var authoredRootMatch = root.querySelector('[' + __hfAuthoredRootAttr + '="' + __hfEscapeAttr(idValue) + '"]');
919
+ if (authoredRootMatch) return authoredRootMatch;
920
+ } catch {}
921
+ if (typeof CSS !== "undefined" && CSS && typeof CSS.escape === "function") {
922
+ try {
923
+ return root.querySelector("#" + CSS.escape(idValue)) || null;
924
+ } catch {}
925
+ }
926
+ try {
927
+ return root.querySelector('[id="' + __hfEscapeAttr(idValue) + '"]') || null;
928
+ } catch {}
929
+ return null;
930
+ };
931
+ var __hfScopedDocument = typeof Proxy === "function"
932
+ ? new Proxy(window.document, {
933
+ get: function(target, prop, receiver) {
934
+ if (prop === "querySelector") return __hfQueryOne;
935
+ if (prop === "querySelectorAll") return __hfQueryAll;
936
+ if (prop === "getElementById") return __hfGetElementById;
937
+ var value = Reflect.get(target, prop, target);
938
+ return typeof value === "function" ? value.bind(target) : value;
939
+ },
940
+ })
941
+ : window.document;
942
+ var __hfTimelineRegistryProxy = null;
943
+ var __hfGetTimelineRegistry = function() {
944
+ window.__timelines = window.__timelines || {};
945
+ if (!__hfCompId || __hfCompId === __hfTimelineCompId || typeof Proxy !== "function") {
946
+ return window.__timelines;
947
+ }
948
+ if (!__hfTimelineRegistryProxy) {
949
+ __hfTimelineRegistryProxy = new Proxy(window.__timelines, {
950
+ get: function(target, prop, receiver) {
951
+ if (prop !== __hfCompId) {
952
+ return Reflect.get(target, prop, target);
953
+ }
954
+ var runtimeValue = Reflect.get(target, __hfTimelineCompId, target);
955
+ return runtimeValue === undefined ? Reflect.get(target, prop, target) : runtimeValue;
956
+ },
957
+ set: function(target, prop, value, receiver) {
958
+ if (prop !== __hfCompId) {
959
+ return Reflect.set(target, prop, value, target);
960
+ }
961
+ // The authored node remains in the compiled DOM when its local id
962
+ // differs from the runtime mount id, so readiness legitimately sees
963
+ // both compositions. Publish the same timeline under both identities,
964
+ // unless another mount of the same file already owns the authored one.
965
+ var authoredValue = Reflect.get(target, __hfCompId, target);
966
+ var ownsAuthored =
967
+ authoredValue === undefined ||
968
+ authoredValue === Reflect.get(target, __hfTimelineCompId, target);
969
+ var runtimeSet = Reflect.set(target, __hfTimelineCompId, value, target);
970
+ if (!ownsAuthored) return runtimeSet;
971
+ return Reflect.set(target, __hfCompId, value, target) && runtimeSet;
972
+ },
973
+ });
974
+ }
975
+ return __hfTimelineRegistryProxy;
976
+ };
977
+ var __hfScopedWindow = typeof Proxy === "function"
978
+ ? new Proxy(window, {
979
+ get: function(target, prop, receiver) {
980
+ if (prop === "__timelines") return __hfGetTimelineRegistry();
981
+ // Inside a sub-composition, __hyperframes is passed as a bare script
982
+ // param bound to the SCOPED variant (per-comp getVariables). But
983
+ // authors routinely write the documented window.__hyperframes.
984
+ // getVariables() form, which would otherwise fall through to the host
985
+ // page's base __hyperframes and return the WRONG (or empty) variables
986
+ // for this instance. Route it to the scoped variant too so both
987
+ // spellings resolve to this composition's own variables.
988
+ // (__hfScopedHyperframes is a hoisted var assigned below, before any
989
+ // sub-comp script -- the only code that reads this -- runs.)
990
+ if (prop === "__hyperframes") return __hfScopedHyperframes;
991
+ // Native window methods must stay bound to the real window. Handed
992
+ // back unbound, "this" at call time is this Proxy and Chrome rejects
993
+ // it with "Illegal invocation", which broke window.addEventListener,
994
+ // setTimeout, matchMedia and getComputedStyle inside every
995
+ // sub-composition -- including the window.addEventListener("hf-seek",
996
+ // ...) form the Three.js and TypeGPU adapters document. The sibling
997
+ // document and gsap proxies here already bind.
998
+ //
999
+ // Only bind non-constructors. Function.prototype.bind drops static
1000
+ // members, so binding a class exposed on window (window.Texts and
1001
+ // friends) would silently strip its statics. Built-in methods have
1002
+ // no .prototype; classes and constructor functions do.
1003
+ var value = Reflect.get(target, prop, target);
1004
+ return typeof value === "function" && value.prototype === undefined
1005
+ ? value.bind(target)
1006
+ : value;
1007
+ },
1008
+ set: function(target, prop, value, receiver) {
1009
+ if (prop === "__timelines") {
1010
+ // Common authoring boilerplate assigns the registry back to
1011
+ // itself (window.__timelines = window.__timelines || {}). The
1012
+ // getter above returns our proxy; do not replace the canonical
1013
+ // registry with that proxy or later wrappers will stack proxies.
1014
+ if (value === __hfTimelineRegistryProxy) return true;
1015
+ target.__timelines = value || {};
1016
+ __hfTimelineRegistryProxy = null;
1017
+ return true;
1018
+ }
1019
+ return Reflect.set(target, prop, value, target);
1020
+ },
1021
+ })
1022
+ : window;
1023
+ var __hfResolveGsapTarget = function(target) {
1024
+ if (typeof target !== "string" && !Array.isArray(target)) return target;
1025
+ var resolved = typeof target === "string" ? __hfQueryAll(target) : target.reduce(function(resolved, item) {
1026
+ if (typeof item === "string") {
1027
+ return resolved.concat(Array.prototype.slice.call(__hfQueryAll(item)));
1028
+ }
1029
+ resolved.push(item);
1030
+ return resolved;
1031
+ }, []);
1032
+ if (!resolved.length) {
1033
+ // GSAP warns "GSAP target " + targets + " not found"; a bare empty match list prints an
1034
+ // empty name. Keep the authored selector as the text while still targeting nothing here.
1035
+ var originalTarget = String(target);
1036
+ resolved = [];
1037
+ resolved.toString = function() { return originalTarget; };
1038
+ }
1039
+ return resolved;
1040
+ };
1041
+ var __hfScopeTimeline = function(timeline) {
1042
+ if (!timeline || timeline.__hfScopedCompositionRoot === __hfFindRoot()) return timeline;
1043
+ ["to", "from", "fromTo", "set"].forEach(function(method) {
1044
+ var original = timeline[method];
1045
+ if (typeof original !== "function") return;
1046
+ timeline[method] = function(target) {
1047
+ var args = Array.prototype.slice.call(arguments);
1048
+ args[0] = __hfResolveGsapTarget(target);
1049
+ return original.apply(timeline, args);
1050
+ };
1051
+ });
1052
+ try {
1053
+ Object.defineProperty(timeline, "__hfScopedCompositionRoot", {
1054
+ value: __hfFindRoot(),
1055
+ configurable: true,
1056
+ });
1057
+ } catch {
1058
+ // Best-effort: timelines coming from user code may have a frozen target
1059
+ // or a non-extensible defineProperty path. Swallow \u2014 the scoped root
1060
+ // is an enrichment, not a correctness invariant for playback.
1061
+ }
1062
+ return timeline;
1063
+ };
1064
+ var __hfBaseGsap = typeof gsap === "undefined" ? window.gsap : gsap;
1065
+ var __hfScopedGsap = !__hfBaseGsap || typeof Proxy !== "function"
1066
+ ? __hfBaseGsap
1067
+ : new Proxy(__hfBaseGsap, {
1068
+ get: function(target, prop, receiver) {
1069
+ if (prop === "timeline") {
1070
+ return function() {
1071
+ return __hfScopeTimeline(target.timeline.apply(target, arguments));
1072
+ };
1073
+ }
1074
+ if (prop === "to" || prop === "from" || prop === "fromTo" || prop === "set") {
1075
+ return function(firstArg) {
1076
+ var args = Array.prototype.slice.call(arguments);
1077
+ args[0] = __hfResolveGsapTarget(firstArg);
1078
+ return target[prop].apply(target, args);
1079
+ };
1080
+ }
1081
+ if (prop === "utils" && target.utils && typeof Proxy === "function") {
1082
+ return new Proxy(target.utils, {
1083
+ get: function(utilsTarget, utilsProp, utilsReceiver) {
1084
+ if (utilsProp === "toArray") {
1085
+ return function(firstArg) {
1086
+ var args = Array.prototype.slice.call(arguments);
1087
+ args[0] = __hfResolveGsapTarget(firstArg);
1088
+ return utilsTarget.toArray.apply(utilsTarget, args);
1089
+ };
1090
+ }
1091
+ if (utilsProp === "selector") {
1092
+ return function(base) {
1093
+ var baseEl = typeof base === "string" ? __hfQueryOne(base) : base;
1094
+ var root = baseEl || __hfFindRoot();
1095
+ return function(selector) {
1096
+ if (!root || typeof selector !== "string") return [];
1097
+ return Array.prototype.filter.call(
1098
+ window.document.querySelectorAll(__hfNormalizeSelector(selector)),
1099
+ function(node) {
1100
+ return node === root || (typeof root.contains === "function" && root.contains(node));
1101
+ },
1102
+ );
1103
+ };
1104
+ };
1105
+ }
1106
+ var value = Reflect.get(utilsTarget, utilsProp, utilsTarget);
1107
+ return typeof value === "function" ? value.bind(utilsTarget) : value;
1108
+ },
1109
+ });
1110
+ }
1111
+ var value = Reflect.get(target, prop, target);
1112
+ return typeof value === "function" ? value.bind(target) : value;
1113
+ },
1114
+ });
1115
+ var __hfBaseHyperframes = window.__hyperframes;
1116
+ var __hfScopedHyperframes = ${SCOPED_HYPERFRAMES_EXPRESSION};
1117
+ var __hfRun = function() {
1118
+ var report = window.__hfScriptState;
1119
+ if (typeof report === "function") report("start", __hfCompositionSrc || "index.html");
1120
+ try {
1121
+ (function(document, gsap, window, __hyperframes) {
1122
+ ${source.replace(/<\/(script)/gi, "<\\/$1")}
1123
+ }).call(window, __hfScopedDocument, __hfScopedGsap, __hfScopedWindow, __hfScopedHyperframes);
1124
+ } catch (_err) {
1125
+ console.error(__hfErrorLabel, __hfCompId, _err);
1126
+ } finally {
1127
+ if (typeof report === "function") report("finish", __hfCompositionSrc || "index.html");
1128
+ }
1129
+ };
1130
+ // What the script started on the global gsap timeline, by any route, for a scene swap to revert.
1131
+ // Only a page with a scene manifest can swap; elsewhere the first script stores null and none records.
1132
+ var __hfRecordAnimations = function(run) {
1133
+ if (window.__hfSceneAnimations === undefined) {
1134
+ window.__hfSceneAnimations = window.document.querySelector(${jsonScriptLiteral(`meta[name="${SCENE_PARTS_META}"]`)})
1135
+ ? {}
1136
+ : null;
1137
+ }
1138
+ var byComp = window.__hfSceneAnimations;
1139
+ var globalTimeline = __hfBaseGsap && __hfBaseGsap.globalTimeline;
1140
+ if (!byComp || !globalTimeline || !__hfTimelineCompId) return run();
1141
+ var before = globalTimeline.getChildren(false);
1142
+ // A set completes as it is made and would leave the timeline before the diff below.
1143
+ var autoRemove = globalTimeline.autoRemoveChildren;
1144
+ globalTimeline.autoRemoveChildren = false;
1145
+ run();
1146
+ globalTimeline.autoRemoveChildren = autoRemove;
1147
+ var recorded = (byComp[__hfTimelineCompId] = byComp[__hfTimelineCompId] || []);
1148
+ globalTimeline.getChildren(false).forEach(function(animation) {
1149
+ if (before.indexOf(animation) >= 0) return;
1150
+ recorded.push(animation);
1151
+ // Dropped as the timeline drops a finished tween (it keeps a paused one); moved back, a tween re-adds itself.
1152
+ if (autoRemove && !animation.getChildren && animation.totalProgress() === 1) globalTimeline.remove(animation);
1153
+ });
1154
+ };
1155
+ __hfFindRoot();
1156
+ __hfRecordAnimations(__hfRun);
1157
+ })();`;
1158
+ }
1159
+ function wrapInlineScriptWithErrorBoundary(source, errorLabel) {
1160
+ return `(function(){ try { Function(${jsonScriptLiteral(source)}).call(window); } catch (_err) { console.error(${jsonScriptLiteral(errorLabel)}, _err); } })();`;
1161
+ }
1162
+ function buildVariablesByCompScript(variablesByComp) {
1163
+ if (!variablesByComp || Object.keys(variablesByComp).length === 0)
1164
+ return null;
1165
+ const json = jsonScriptLiteral(variablesByComp);
1166
+ return `window.__hfVariablesByComp = Object.assign({}, window.__hfVariablesByComp || {}, ${json});`;
1167
+ }
1168
+
1169
+ // ../core/dist/compiler/staticGuard.js
1170
+ async function validateHyperframeHtmlContract(html) {
1171
+ const result = await lintHyperframeHtml(html);
1172
+ const missingKeys = result.findings.filter((finding) => finding.severity === "error").map((finding) => finding.message);
1173
+ if (missingKeys.length === 0) {
1174
+ return { isValid: true, missingKeys: [], failureReason: null };
1175
+ }
1176
+ const joined = missingKeys.join(" ").toLowerCase();
1177
+ let failureReason = "invalid_static_hyperframe_contract";
1178
+ if (joined.includes("data-composition-id")) {
1179
+ failureReason = "missing_composition_id";
1180
+ } else if (joined.includes("data-width") || joined.includes("data-height")) {
1181
+ failureReason = "missing_composition_dimensions";
1182
+ } else if (joined.includes("window.__timelines")) {
1183
+ failureReason = "missing_timeline_registry";
1184
+ } else if (joined.includes("script syntax")) {
1185
+ failureReason = "invalid_script_syntax";
1186
+ }
1187
+ return { isValid: false, missingKeys, failureReason };
1188
+ }
1189
+
1190
+ // ../core/dist/compiler/svgSelectorAliases.js
1191
+ var SVG_REFERENCE_ALIASES_ATTR = "data-hf-svg-reference-aliases";
1192
+ function rewriteSvgSelectors(selector, ids, references, namespaces) {
1193
+ const attributeOperators = {
1194
+ "=": (before, value) => before === value,
1195
+ "~=": (before, value) => before.split(/[ \t\r\n\f]+/).includes(value),
1196
+ "|=": (before, value) => before === value || before.startsWith(value + "-"),
1197
+ "^=": (before, value) => before.startsWith(value),
1198
+ "$=": (before, value) => before.endsWith(value),
1199
+ "*=": (before, value) => before.includes(value)
1200
+ };
1201
+ const matchesValue = (before, value, operator) => {
1202
+ if (!value && operator !== "=" && operator !== "|=")
1203
+ return false;
1204
+ return attributeOperators[operator](before, value);
1205
+ };
1206
+ const lower = (text) => text.replace(/[A-Z]/g, (char) => char.toLowerCase());
1207
+ const rewriteAttribute = (predicate) => {
1208
+ const parsed = parseAttributeSelector(predicate);
1209
+ if (!parsed)
1210
+ return predicate;
1211
+ const { name, rawName, namespace, operator, value, flag } = parsed;
1212
+ if (namespace.kind === "named" !== (namespaces !== void 0))
1213
+ return predicate;
1214
+ const fold = flag?.toLowerCase() === "i" ? lower : (text) => text;
1215
+ const attributeName = lower(name);
1216
+ const candidates = references.filter((reference) => {
1217
+ const actualName = namespace.kind === "none" ? reference.name : reference.localName;
1218
+ const uri = namespace.kind === "named" ? namespaces.get(namespace.prefix) : null;
1219
+ return (namespace.kind === "any" || reference.namespaceURI === uri) && lower(actualName) === attributeName;
1220
+ });
1221
+ const alternatives = /* @__PURE__ */ new Set([predicate]);
1222
+ for (const reference of candidates) {
1223
+ if (!matchesValue(fold(reference.before), fold(value), operator))
1224
+ continue;
1225
+ alternatives.add(`[${rawName}="${escapeCssAttributeValue(reference.after)}"${flag ? ` ${flag}` : ""}]`);
1226
+ }
1227
+ return alternatives.size === 1 ? predicate : `:is(${[...alternatives].join(", ")})`;
1228
+ };
1229
+ if (namespaces)
1230
+ return replaceSelectorAttributeTokens(selector, rewriteAttribute);
1231
+ const replacements = new Map(ids.map(({ id, replacement }) => [id, replacement]));
1232
+ const targets = /* @__PURE__ */ new Map();
1233
+ for (const reference of references) {
1234
+ if (reference.name !== "id" || reference.before === reference.after || replacements.has(reference.before))
1235
+ continue;
1236
+ let alternatives = targets.get(reference.before);
1237
+ if (!alternatives) {
1238
+ alternatives = /* @__PURE__ */ new Set([`#${escapeCssIdentifier(reference.before)}`]);
1239
+ targets.set(reference.before, alternatives);
1240
+ }
1241
+ alternatives.add(`#${escapeCssIdentifier(reference.after)}`);
1242
+ }
1243
+ for (const [id, alternatives] of targets)
1244
+ replacements.set(id, `:is(${[...alternatives].join(", ")})`);
1245
+ const rewrittenIds = replaceSelectorIdTokens(selector, [...replacements.keys()], (id) => replacements.get(id));
1246
+ return replaceSelectorAttributeTokens(rewrittenIds, rewriteAttribute);
1247
+ }
1248
+ function readSvgReferenceAliases(root, attribute, includeDescendants = true) {
1249
+ const aliases = [];
1250
+ const nodes = includeDescendants ? [...root.querySelectorAll(`[${attribute}]`)] : [];
1251
+ const texts = nodes.map((node) => node.getAttribute(attribute));
1252
+ const own = root.getAttribute?.(attribute);
1253
+ if (own)
1254
+ texts.unshift(own);
1255
+ for (const text of texts) {
1256
+ let value;
1257
+ try {
1258
+ value = JSON.parse(text);
1259
+ } catch {
1260
+ continue;
1261
+ }
1262
+ if (!Array.isArray(value))
1263
+ continue;
1264
+ const entries = value;
1265
+ for (const entry of entries) {
1266
+ if (!isSvgReferenceAlias(entry))
1267
+ continue;
1268
+ const { name, localName, namespaceURI, before, after } = entry;
1269
+ aliases.push({ name, localName, namespaceURI, before, after });
1270
+ }
1271
+ }
1272
+ return aliases;
1273
+ }
1274
+ function isSvgReferenceAlias(entry) {
1275
+ if (!entry || typeof entry !== "object")
1276
+ return false;
1277
+ const { name, localName, namespaceURI, before, after } = entry;
1278
+ return typeof name === "string" && typeof localName === "string" && (namespaceURI === null || typeof namespaceURI === "string") && typeof before === "string" && typeof after === "string";
1279
+ }
1280
+
1281
+ // ../core/dist/compiler/svgIdNamespacing.js
1282
+ import postcss2 from "postcss";
1283
+ var ID_ATTR = "id";
1284
+ var SVG_AUTHORED_ID_ATTR = "data-hf-authored-id";
1285
+ var URL_HASH_REF_RE = /(url\(\s*)(["']?)#([^"')\s]+)\2(\s*\))/gi;
1286
+ function isHrefAttrName(name) {
1287
+ return name === "href" || name.endsWith(":href");
1288
+ }
1289
+ function sanitizeNamespaceSegment(value) {
1290
+ return value.replace(/[^a-zA-Z0-9_-]/g, "-");
1291
+ }
1292
+ function rewriteUrlHashRefs(value, idMap) {
1293
+ if (!value || !value.toLowerCase().includes("url("))
1294
+ return value;
1295
+ return value.replace(URL_HASH_REF_RE, (full, pre, quote, id, post) => {
1296
+ const mapped = idMap.get(id);
1297
+ return mapped ? `${pre}${quote}#${mapped}${quote}${post}` : full;
1298
+ });
1299
+ }
1300
+ function nativeReferenceValue(name, value, idMap) {
1301
+ if (isHrefAttrName(name) && value.startsWith("#")) {
1302
+ const mapped = idMap.get(value.slice(1));
1303
+ return mapped ? `#${mapped}` : value;
1304
+ }
1305
+ URL_HASH_REF_RE.lastIndex = 0;
1306
+ const hasUrl = URL_HASH_REF_RE.test(value);
1307
+ URL_HASH_REF_RE.lastIndex = 0;
1308
+ return hasUrl ? rewriteUrlHashRefs(value, idMap) : null;
1309
+ }
1310
+ function decideReferenceWrite(attr, previous, idMap) {
1311
+ if (attr.name === SVG_REFERENCE_ALIASES_ATTR || attr.name === ID_ATTR)
1312
+ return { kind: "skip" };
1313
+ const before = previous && attr.value === previous.after ? previous.before : attr.value;
1314
+ const after = nativeReferenceValue(attr.name, before, idMap);
1315
+ if (after !== null)
1316
+ return { kind: "managed", before, after };
1317
+ return previous ? { kind: "retain", alias: previous } : { kind: "skip" };
1318
+ }
1319
+ function referenceAlias(attr, before, after, inSvg) {
1320
+ const serializedXlink = attr.namespaceURI === void 0 && attr.name === "xlink:href" && inSvg;
1321
+ return {
1322
+ name: attr.name,
1323
+ localName: serializedXlink ? "href" : attr.localName,
1324
+ namespaceURI: serializedXlink ? "http://www.w3.org/1999/xlink" : attr.namespaceURI ?? null,
1325
+ before,
1326
+ after
1327
+ };
1328
+ }
1329
+ function rewriteElementIdReferences(el, idMap) {
1330
+ const prior = new Map(readSvgReferenceAliases(el, SVG_REFERENCE_ALIASES_ATTR, false).map((alias) => [
1331
+ alias.name,
1332
+ alias
1333
+ ]));
1334
+ const aliases = [...prior.values()].filter((alias) => alias.name === ID_ATTR);
1335
+ const inSvg = !!el.closest("svg");
1336
+ for (const attr of el.attributes ? Array.from(el.attributes) : []) {
1337
+ const decision = decideReferenceWrite(attr, prior.get(attr.name), idMap);
1338
+ if (decision.kind === "skip")
1339
+ continue;
1340
+ if (decision.kind === "retain") {
1341
+ aliases.push(decision.alias);
1342
+ continue;
1343
+ }
1344
+ if (decision.after !== attr.value) {
1345
+ if (attr.namespaceURI)
1346
+ el.setAttributeNS(attr.namespaceURI, attr.name, decision.after);
1347
+ else
1348
+ el.setAttribute(attr.name, decision.after);
1349
+ }
1350
+ aliases.push(referenceAlias(attr, decision.before, decision.after, inSvg));
1351
+ }
1352
+ if (aliases.length)
1353
+ el.setAttribute(SVG_REFERENCE_ALIASES_ATTR, JSON.stringify(aliases));
1354
+ }
1355
+ function collectUrlHashRefsFromText(text, filter, out) {
1356
+ let m;
1357
+ URL_HASH_REF_RE.lastIndex = 0;
1358
+ while (m = URL_HASH_REF_RE.exec(text)) {
1359
+ const refId = m[3];
1360
+ if (filter.has(refId))
1361
+ out.add(refId);
1362
+ }
1363
+ }
1364
+ function collectHrefFragmentRef(attr, filter, out) {
1365
+ if (isHrefAttrName(attr.name) && attr.value.startsWith("#")) {
1366
+ const id = attr.value.slice(1);
1367
+ if (filter.has(id))
1368
+ out.add(id);
1369
+ }
1370
+ }
1371
+ function collectNativelyReferencedIds(elements, cssTexts, svgIds) {
1372
+ const referenced = /* @__PURE__ */ new Set();
1373
+ for (const el of elements) {
1374
+ for (const attr of el.attributes ? Array.from(el.attributes) : []) {
1375
+ if (!attr.value || attr.name === SVG_REFERENCE_ALIASES_ATTR)
1376
+ continue;
1377
+ collectHrefFragmentRef(attr, svgIds, referenced);
1378
+ if (attr.value.toLowerCase().includes("url("))
1379
+ collectUrlHashRefsFromText(attr.value, svgIds, referenced);
1380
+ }
1381
+ }
1382
+ for (const text of cssTexts) {
1383
+ if (text.toLowerCase().includes("url("))
1384
+ collectUrlHashRefsFromText(text, svgIds, referenced);
1385
+ }
1386
+ return referenced;
1387
+ }
1388
+ function isExcluded(el, exclude) {
1389
+ return exclude.some((excluded) => excluded === el || excluded.contains(el));
1390
+ }
1391
+ function collectScopeElements(scope) {
1392
+ const exclude = scope.exclude ?? [];
1393
+ const descendants = [...scope.root.querySelectorAll("*")];
1394
+ const own = exclude.length ? descendants.filter((el) => !isExcluded(el, exclude)) : descendants;
1395
+ return [scope.root, ...own];
1396
+ }
1397
+ function collectSvgIdElements(scope) {
1398
+ const exclude = scope.exclude ?? [];
1399
+ const matches = [...scope.root.querySelectorAll("svg [id], svg[id]")];
1400
+ return exclude.length ? matches.filter((el) => !isExcluded(el, exclude)) : matches;
1401
+ }
1402
+ function resolveScope(scope) {
1403
+ const elements = collectScopeElements(scope);
1404
+ const renamable = /* @__PURE__ */ new Set();
1405
+ if (!scope.namespace)
1406
+ return { elements, renamable };
1407
+ const svgIdElements = collectSvgIdElements(scope);
1408
+ const svgIds = /* @__PURE__ */ new Set();
1409
+ for (const el of svgIdElements) {
1410
+ const id = el.getAttribute(ID_ATTR);
1411
+ if (id)
1412
+ svgIds.add(id);
1413
+ }
1414
+ if (svgIds.size === 0)
1415
+ return { elements, renamable };
1416
+ const nativelyReferenced = collectNativelyReferencedIds(elements, scope.cssTexts ?? [], svgIds);
1417
+ for (const el of svgIdElements) {
1418
+ const id = el.getAttribute(ID_ATTR);
1419
+ if (id && nativelyReferenced.has(id))
1420
+ renamable.add(el);
1421
+ }
1422
+ return { elements, renamable };
1423
+ }
1424
+ function currentAuthoredSvgId(el) {
1425
+ if (!el.closest("svg"))
1426
+ return null;
1427
+ const idWrite = readSvgReferenceAliases(el, SVG_REFERENCE_ALIASES_ATTR, false).find((alias) => alias.name === ID_ATTR);
1428
+ if (idWrite)
1429
+ return el.getAttribute(ID_ATTR) === idWrite.after ? idWrite.before : null;
1430
+ return el.getAttribute(SVG_AUTHORED_ID_ATTR);
1431
+ }
1432
+ function buildIdCensus(document) {
1433
+ const elementsById = /* @__PURE__ */ new Map();
1434
+ const usedIds = /* @__PURE__ */ new Set();
1435
+ for (const el of document.querySelectorAll("[id]")) {
1436
+ const id = el.getAttribute(ID_ATTR);
1437
+ if (!id)
1438
+ continue;
1439
+ usedIds.add(id);
1440
+ const list = elementsById.get(id);
1441
+ if (list)
1442
+ list.push(el);
1443
+ else
1444
+ elementsById.set(id, [el]);
1445
+ const authored = currentAuthoredSvgId(el);
1446
+ if (authored && authored !== id) {
1447
+ const aliases = elementsById.get(authored);
1448
+ if (aliases)
1449
+ aliases.push(el);
1450
+ else
1451
+ elementsById.set(authored, [el]);
1452
+ }
1453
+ }
1454
+ return { elementsById, usedIds };
1455
+ }
1456
+ function mintNamespacedId(namespace, originalId, usedIds) {
1457
+ const base = `${sanitizeNamespaceSegment(namespace)}--${originalId}`;
1458
+ let candidate = base;
1459
+ for (let n = 2; usedIds.has(candidate); n += 1)
1460
+ candidate = `${base}-${n}`;
1461
+ usedIds.add(candidate);
1462
+ return candidate;
1463
+ }
1464
+ function collisionScopes(id, elements, scopeIndexByRenamable) {
1465
+ const keeper = elements.find((el) => !scopeIndexByRenamable.has(el)) ?? elements[0];
1466
+ const candidates = elements.filter((el) => el !== keeper && el.getAttribute(ID_ATTR) === id);
1467
+ const indices = candidates.map((el) => scopeIndexByRenamable.get(el));
1468
+ return new Set(indices.filter((index) => index !== void 0));
1469
+ }
1470
+ function planRenames(census, scopes, scopeIndexByRenamable) {
1471
+ const idMaps = scopes.map(() => /* @__PURE__ */ new Map());
1472
+ for (const [id, elements] of census.elementsById) {
1473
+ if (elements.length < 2)
1474
+ continue;
1475
+ for (const index of collisionScopes(id, elements, scopeIndexByRenamable)) {
1476
+ idMaps[index].set(id, mintNamespacedId(scopes[index].namespace, id, census.usedIds));
1477
+ }
1478
+ }
1479
+ return idMaps;
1480
+ }
1481
+ function documentReferenceTargets(census, idMaps, scopeIndexByRenamable) {
1482
+ const targets = /* @__PURE__ */ new Map();
1483
+ for (const [id, elements] of census.elementsById) {
1484
+ const target = elements[0];
1485
+ const actual = target.getAttribute(ID_ATTR);
1486
+ if (actual !== id) {
1487
+ targets.set(id, actual);
1488
+ continue;
1489
+ }
1490
+ const index = scopeIndexByRenamable.get(target);
1491
+ const renamed = index === void 0 ? void 0 : idMaps[index].get(id);
1492
+ if (renamed)
1493
+ targets.set(id, renamed);
1494
+ }
1495
+ return targets;
1496
+ }
1497
+ function localReferenceBindings(elements) {
1498
+ const ids = new Set(elements.map((el) => el.getAttribute(ID_ATTR)));
1499
+ const renamed = /* @__PURE__ */ new Map();
1500
+ for (const el of elements) {
1501
+ const authored = currentAuthoredSvgId(el);
1502
+ const current = el.getAttribute(ID_ATTR);
1503
+ if (!authored || !current)
1504
+ continue;
1505
+ ids.add(authored);
1506
+ renamed.set(authored, current);
1507
+ }
1508
+ return { ids, renamed };
1509
+ }
1510
+ function applyRenames(resolved, idMap) {
1511
+ for (const el of resolved.elements) {
1512
+ const currentId = el.getAttribute(ID_ATTR);
1513
+ if (currentId && resolved.renamable.has(el) && idMap.has(currentId)) {
1514
+ if (!el.hasAttribute(SVG_AUTHORED_ID_ATTR))
1515
+ el.setAttribute(SVG_AUTHORED_ID_ATTR, currentId);
1516
+ const after = idMap.get(currentId);
1517
+ const aliases = readSvgReferenceAliases(el, SVG_REFERENCE_ALIASES_ATTR, false);
1518
+ aliases.push({
1519
+ name: ID_ATTR,
1520
+ localName: ID_ATTR,
1521
+ namespaceURI: null,
1522
+ before: currentId,
1523
+ after
1524
+ });
1525
+ el.setAttribute(SVG_REFERENCE_ALIASES_ATTR, JSON.stringify(aliases));
1526
+ el.setAttribute(ID_ATTR, after);
1527
+ }
1528
+ rewriteElementIdReferences(el, idMap);
1529
+ }
1530
+ }
1531
+ function namespaceCollidingSvgIds(document, scopes, finalizedIds) {
1532
+ if (scopes.length === 0)
1533
+ return [];
1534
+ const census = buildIdCensus(document);
1535
+ const resolved = scopes.map(resolveScope);
1536
+ const newlyEligible = resolved.flatMap(({ renamable }) => [...renamable]);
1537
+ if (finalizedIds) {
1538
+ for (const scope of resolved) {
1539
+ for (const el of scope.renamable)
1540
+ if (finalizedIds.has(el))
1541
+ scope.renamable.delete(el);
1542
+ }
1543
+ }
1544
+ const scopeIndexByRenamable = /* @__PURE__ */ new Map();
1545
+ resolved.forEach(({ renamable }, index) => {
1546
+ for (const el of renamable)
1547
+ scopeIndexByRenamable.set(el, index);
1548
+ });
1549
+ const idMaps = planRenames(census, scopes, scopeIndexByRenamable);
1550
+ const documentTargets = documentReferenceTargets(census, idMaps, scopeIndexByRenamable);
1551
+ const referenceMaps = resolved.map((scope, index) => {
1552
+ const local = localReferenceBindings(scopes[index].referenceTarget === "document" ? [] : scope.elements);
1553
+ const inherited = [...documentTargets].filter(([id]) => !local.ids.has(id));
1554
+ return new Map([...inherited, ...local.renamed, ...idMaps[index]]);
1555
+ });
1556
+ referenceMaps.forEach((idMap, index) => {
1557
+ applyRenames(resolved[index], idMap);
1558
+ });
1559
+ for (const el of newlyEligible)
1560
+ finalizedIds?.add(el);
1561
+ return referenceMaps;
1562
+ }
1563
+ function rewriteSvgIdReferencesInCss(css, idMap, references = []) {
1564
+ if (!css || idMap.size === 0 && references.length === 0)
1565
+ return css;
1566
+ if (!css.includes("#") && !css.includes("[") && !css.toLowerCase().includes("url("))
1567
+ return css;
1568
+ let root;
1569
+ try {
1570
+ root = postcss2.parse(css);
1571
+ } catch {
1572
+ return css;
1573
+ }
1574
+ let mutated = false;
1575
+ const recordedIds = new Set(references.filter((alias) => alias.name === ID_ATTR).map((alias) => alias.before));
1576
+ const ids = [...idMap].filter(([id]) => !recordedIds.has(id)).map(([id, renamed]) => ({
1577
+ id,
1578
+ replacement: `:is(#${escapeCssIdentifier(id)}, #${escapeCssIdentifier(renamed)})`
1579
+ }));
1580
+ root.walkRules((rule) => {
1581
+ const rewritten = rule.selectors.map((selector) => rewriteSvgSelectors(selector, ids, references));
1582
+ if (rewritten.some((selector, index) => selector !== rule.selectors[index])) {
1583
+ rule.selectors = rewritten;
1584
+ mutated = true;
1585
+ }
1586
+ });
1587
+ root.walkDecls((decl) => {
1588
+ const rewritten = rewriteUrlHashRefs(decl.value, idMap);
1589
+ if (rewritten !== decl.value) {
1590
+ decl.value = rewritten;
1591
+ mutated = true;
1592
+ }
1593
+ });
1594
+ root.walkAtRules((atRule) => {
1595
+ if (!atRule.params)
1596
+ return;
1597
+ const rewritten = rewriteUrlHashRefs(atRule.params, idMap);
1598
+ if (rewritten !== atRule.params) {
1599
+ atRule.params = rewritten;
1600
+ mutated = true;
1601
+ }
1602
+ });
1603
+ return mutated ? root.toResult({ map: false }).css : css;
1604
+ }
1605
+
1606
+ // ../core/dist/compiler/inlineSubCompositions.js
1607
+ var SIDE_EFFECT_RE = /\b(addEventListener|requestAnimationFrame|requestIdleCallback|setTimeout|setInterval|queueMicrotask|getContext|WebGL\w*|WebGPU\w*|gpu|Worker|WebSocket|EventSource|Audio\w*|\w*Observer|fetch|import|eval|Function|Promise|async|await|delayedCall|ScrollTrigger|Draggable|anime|customElements|registerProperty|addListener|BroadcastChannel|pushState|replaceState|adoptedStyleSheets|documentElement|getElementsByTagName|lottie|THREE|__hf[A-Z]\w*)\b|\.then\s*\(|\.animate\s*\(|\.ticker\b|repeat\s*:\s*-1|\.repeat\s*\(\s*-1|defineProperty\s*\(\s*(window|globalThis|self|document)\b|\bfonts\s*\.\s*add\b|\.on[a-z]+\s*=(?!=)|\bon(resize|scroll|message|key\w+|click|pointer\w+|mouse\w+|wheel|visibilitychange|hashchange|popstate|error|load)\s*=(?!=)|\[\s*["']on[a-z]+["']\s*\]|document\s*\.\s*(head|body)\b|querySelector(All)?\(\s*["'](head|body)["']|\bgsap\s*\.\s*(?:to|from|fromTo)\s*\(|\bgsap\s*\.\s*timeline\s*\((?:[^()]|\([^()]*\))*\)\s*\.\s*(?:to|from|fromTo|set|add|call)\s*\(/;
1608
+ var SWAP_SAFE_LIBRARY_URL = /^https:\/\/(cdn\.jsdelivr\.net\/npm|unpkg\.com)\/(gsap|three|d3|d3-[a-z-]+|topojson-client|clipper-lib)(@[^/]+)?\//;
1609
+ var isSwapSafeLibrary = (src) => URL.canParse(src) && SWAP_SAFE_LIBRARY_URL.test(new URL(src).href);
1610
+ function sceneScriptSwapRefusal(script) {
1611
+ const match = SIDE_EFFECT_RE.exec(script);
1612
+ return match ? `its script uses ${match[0].trim()}` : null;
1613
+ }
1614
+ var STRING_LITERAL_RE = /(["'`])((?:\\.|(?!\1)[^\\\n])*?)\1/g;
1615
+ var CREATES_ELEMENT_RE = /createElement\s*\(\s*$|createElementNS\s*\([^()]*,\s*$/;
1616
+ var isNotASelector = (script, at, literal) => CREATES_ELEMENT_RE.test(script.slice(Math.max(0, at - 60), at)) || literal.trim() === "*" && /,\s*$/.test(script.slice(Math.max(0, at - 20), at));
1617
+ function refuseSwapsReachedByRootScripts(document, rootScripts) {
1618
+ const hosts = [...document.querySelectorAll(`[${SCENE_PART_ATTR}]`)];
1619
+ const byName = /* @__PURE__ */ new Map();
1620
+ for (const host of hosts) {
1621
+ for (const el of [host, ...host.querySelectorAll("*")]) {
1622
+ for (const name of [
1623
+ el.localName,
1624
+ el.id && `#${el.id}`,
1625
+ ...[...el.classList].map((c) => `.${c}`)
1626
+ ]) {
1627
+ if (name)
1628
+ byName.set(name, (byName.get(name) ?? /* @__PURE__ */ new Set()).add(host));
1629
+ }
1630
+ }
1631
+ }
1632
+ const namesKnown = (selector) => selector.split(",").some((alt) => alt.split(/[\s>+~]+/).every((part) => !/^[a-z][\w-]*$/i.test(part) || byName.has(part.toLowerCase()) || document.querySelector(part) !== null));
1633
+ const literals = new Set(rootScripts.flatMap((s) => [...s.matchAll(STRING_LITERAL_RE)].filter((m) => !isNotASelector(s, m.index, m[2] ?? "")).map((m) => m[2] ?? "")));
1634
+ for (const literal of literals) {
1635
+ const open = hosts.filter((host) => !host.hasAttribute(SCENE_NO_SWAP_ATTR));
1636
+ if (open.length === 0)
1637
+ return;
1638
+ const reached = literal.trim() === "*" ? open : /^[A-Za-z_][\w-]*$/.test(literal) ? [literal.toLowerCase(), `#${literal}`, `.${literal}`].flatMap((name) => [
1639
+ ...byName.get(name) ?? []
1640
+ ]) : /[#.[:>]|[\w\]*] *[\s,]+ *[\w*]/.test(literal) && literal.length <= 120 && namesKnown(literal) ? open.filter((host) => reaches(host, literal)) : [];
1641
+ for (const host of reached)
1642
+ if (!host.hasAttribute(SCENE_NO_SWAP_ATTR))
1643
+ host.setAttribute(SCENE_NO_SWAP_ATTR, `a script outside the scene selects ${literal}`);
1644
+ }
1645
+ }
1646
+ var reaches = (host, selector) => {
1647
+ try {
1648
+ return host.matches(selector) || host.querySelector(selector) !== null;
1649
+ } catch {
1650
+ return false;
1651
+ }
1652
+ };
1653
+ function ensureExternalLinkTag(doc, link) {
1654
+ const el = doc.createElement("link");
1655
+ el.setAttribute("rel", link.rel);
1656
+ el.setAttribute("href", link.href);
1657
+ for (const name of ["crossorigin", "media", "title", "type"]) {
1658
+ const value = link[name];
1659
+ if (value != null)
1660
+ el.setAttribute(name, value);
1661
+ }
1662
+ if (link.disabled)
1663
+ el.setAttribute("disabled", "");
1664
+ if (!hasSameLink(doc, el))
1665
+ doc.head.appendChild(el);
1666
+ }
1667
+ var isDocument = (node) => node.nodeType === 9;
1668
+ function defaultBuildScopeSelector(compId) {
1669
+ const escaped = compId.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
1670
+ return `[data-composition-id="${escaped}"]`;
1671
+ }
1672
+ function inlineSubCompositions(document, hosts, options) {
1673
+ const { resolveHtml, parseHtml, hostIdentityMap, rewriteInlineStyles = false, flattenInnerRoot, compoundAuthoredRoot, readVariableDefaults, parseHostVariables, buildScopeSelector = defaultBuildScopeSelector, scriptErrorLabel = "[Framey] composition script error:", onMissingComposition, assetExists, tagScenes = false } = options;
1674
+ const rootStyles = [...document.querySelectorAll("style")];
1675
+ const styles = [];
1676
+ const styleScenes = [];
1677
+ const scripts = [];
1678
+ const externalScriptSrcs = [];
1679
+ const scriptItems = [];
1680
+ const importMaps = [];
1681
+ const moduleScripts = [];
1682
+ const externalLinks = [];
1683
+ const variablesByComp = {};
1684
+ const svgIdScopes = [];
1685
+ const parsed = /* @__PURE__ */ new Map();
1686
+ const parseOnce = (html) => {
1687
+ let doc = parsed.get(html);
1688
+ if (!doc) {
1689
+ doc = parseHtml(html);
1690
+ parsed.set(html, doc);
1691
+ }
1692
+ return doc;
1693
+ };
1694
+ const parseCopy = (html) => {
1695
+ const copy = parseOnce(html).cloneNode(true);
1696
+ return isDocument(copy) ? copy : parseHtml(html);
1697
+ };
1698
+ const usability = /* @__PURE__ */ new Map();
1699
+ const sheetsWithAssetUrls = /* @__PURE__ */ new Map();
1700
+ const scopeCssToComposition2 = createCompositionCssScoper();
1701
+ const sceneHosts = /* @__PURE__ */ new Map();
1702
+ const queue = hosts.map((element) => ({
1703
+ element,
1704
+ ancestry: [],
1705
+ scene: void 0
1706
+ }));
1707
+ for (let queueIndex = 0; queueIndex < queue.length; queueIndex += 1) {
1708
+ const { element: hostEl, ancestry, scene: parentScene } = queue[queueIndex];
1709
+ const src = hostEl.getAttribute("data-composition-src");
1710
+ if (!src)
1711
+ continue;
1712
+ const compHtml = resolveHtml(src);
1713
+ let validity = compHtml == null ? void 0 : usability.get(compHtml);
1714
+ if (!validity) {
1715
+ validity = checkSubCompositionUsability(compHtml, parseOnce);
1716
+ if (compHtml != null)
1717
+ usability.set(compHtml, validity);
1718
+ }
1719
+ if (!validity.ok) {
1720
+ onMissingComposition?.(src, validity.detail);
1721
+ continue;
1722
+ }
1723
+ if (compHtml == null) {
1724
+ onMissingComposition?.(src);
1725
+ continue;
1726
+ }
1727
+ const compDoc = parseCopy(compHtml);
1728
+ let compId;
1729
+ let runtimeCompId;
1730
+ if (hostIdentityMap) {
1731
+ const identity = hostIdentityMap.get(hostEl);
1732
+ compId = identity?.authoredCompositionId || null;
1733
+ runtimeCompId = identity?.runtimeCompositionId || compId || "";
1734
+ } else {
1735
+ compId = hostEl.getAttribute("data-composition-id") || null;
1736
+ runtimeCompId = compId || "";
1737
+ }
1738
+ const { contentHtml, hasTemplate } = resolveSubCompositionContent(compHtml, compDoc);
1739
+ if (!contentHtml.trim()) {
1740
+ onMissingComposition?.(src);
1741
+ continue;
1742
+ }
1743
+ const contentDoc = parseCopy(contentHtml);
1744
+ if (!contentDoc.documentElement) {
1745
+ onMissingComposition?.(src);
1746
+ continue;
1747
+ }
1748
+ const plan = planCompositionAssembly({
1749
+ contentNode: contentDoc,
1750
+ head: compDoc.head,
1751
+ documentElement: compDoc.documentElement,
1752
+ hasTemplate,
1753
+ compositionId: compId
1754
+ });
1755
+ const innerRoot = plan.innerRoot;
1756
+ const authoredRootId = plan.authoredRootId;
1757
+ const scopeCompId = plan.authoredCompositionId || "";
1758
+ const scriptCompositionId = plan.scriptCompositionId || "";
1759
+ const runtimeScope = runtimeCompId ? buildScopeSelector(runtimeCompId) : "";
1760
+ const scene = tagScenes ? parentScene ?? (runtimeCompId || src) : void 0;
1761
+ if (scene && !parentScene) {
1762
+ hostEl.setAttribute(SCENE_PART_ATTR, scene);
1763
+ sceneHosts.set(scene, hostEl);
1764
+ }
1765
+ const refuseSwap = (why) => {
1766
+ const host = scene ? sceneHosts.get(scene) : void 0;
1767
+ if (!host || host.hasAttribute(SCENE_NO_SWAP_ATTR))
1768
+ return;
1769
+ const reason = why();
1770
+ if (reason)
1771
+ host.setAttribute(SCENE_NO_SWAP_ATTR, reason);
1772
+ };
1773
+ if (readVariableDefaults && parseHostVariables && runtimeCompId) {
1774
+ const mergedVariables = {};
1775
+ for (const carrier of plan.variableDefaultCarriers) {
1776
+ Object.assign(mergedVariables, readVariableDefaults(carrier));
1777
+ }
1778
+ Object.assign(mergedVariables, parseHostVariables(hostEl));
1779
+ if (Object.keys(mergedVariables).length > 0) {
1780
+ variablesByComp[runtimeCompId] = mergedVariables;
1781
+ }
1782
+ warnUnknownEnumValues(compDoc.documentElement, mergedVariables, runtimeCompId);
1783
+ warnUnknownEnumValues(innerRoot, mergedVariables, runtimeCompId);
1784
+ }
1785
+ const resolveSubAssetPath = (raw) => rewriteAssetPath(src, (raw || "").trim(), assetExists);
1786
+ const scopeSubStyle = (raw) => {
1787
+ const sheetKey = JSON.stringify([src, raw]);
1788
+ let css = sheetsWithAssetUrls.get(sheetKey);
1789
+ if (css === void 0) {
1790
+ css = rewriteCssAssetUrls(raw, src, assetExists);
1791
+ sheetsWithAssetUrls.set(sheetKey, css);
1792
+ }
1793
+ return scopeCompId ? scopeCssToComposition2(css, scopeCompId, runtimeScope || void 0, authoredRootId, {
1794
+ compoundAuthoredRoot: compoundAuthoredRoot === true,
1795
+ scopeRootSelectors: true
1796
+ }) : css;
1797
+ };
1798
+ for (const link of plan.linkSources) {
1799
+ const href = resolveSubAssetPath(link.getAttribute("href"));
1800
+ if (href) {
1801
+ const rel = (link.getAttribute("rel") || "").trim();
1802
+ const crossorigin = link.hasAttribute("crossorigin") ? link.getAttribute("crossorigin") || "" : void 0;
1803
+ const media = link.getAttribute("media") ?? void 0;
1804
+ const title = link.getAttribute("title") ?? void 0;
1805
+ const type = link.getAttribute("type") ?? void 0;
1806
+ const disabled = link.hasAttribute("disabled") ? true : void 0;
1807
+ externalLinks.push({ href, rel, crossorigin, media, title, type, disabled });
1808
+ }
1809
+ }
1810
+ const styleStart = styles.length;
1811
+ for (const styleEl of plan.styleSources) {
1812
+ if (cssStyleMergeKey(styleEl) === void 0)
1813
+ continue;
1814
+ styles.push(compositionStyle(styleEl, scopeSubStyle(styleEl.textContent || "")));
1815
+ if (scene)
1816
+ styleScenes.push(scene);
1817
+ styleEl.remove();
1818
+ }
1819
+ const styleEnd = styles.length;
1820
+ for (const scriptEl of plan.scriptSources) {
1821
+ const externalSrc = resolveSubAssetPath(scriptEl.getAttribute("src"));
1822
+ const type = (scriptEl.getAttribute("type") || "").trim().toLowerCase();
1823
+ refuseSwap(() => type === "importmap" || type === "module" ? "it runs a module script or import map" : !externalSrc ? sceneScriptSwapRefusal(scriptEl.textContent || "") : isSwapSafeLibrary(externalSrc) ? null : "it runs a script that is not a known library");
1824
+ if (type === "importmap") {
1825
+ const map = parseImportMap(scriptEl.textContent || "", (url) => {
1826
+ const authored = url.trim();
1827
+ const rebased = resolveSubAssetPath(authored);
1828
+ if (rebased === authored)
1829
+ return rebased;
1830
+ const urlLike = /^(\/|\.\.?\/|[a-z][a-z\d+.-]*:)/i.test(rebased) ? rebased : `./${rebased}`;
1831
+ return authored.endsWith("/") && !urlLike.endsWith("/") ? `${urlLike}/` : urlLike;
1832
+ });
1833
+ if (map)
1834
+ importMaps.push(map);
1835
+ else
1836
+ console.warn(`[Framey] ${src}: import map is not valid JSON, so it is skipped.`);
1837
+ } else if (type === "module" && !externalSrc) {
1838
+ const prelude = scriptCompositionId ? scopedModulePrelude(runtimeCompId || scopeCompId || scriptCompositionId, src) : "";
1839
+ moduleScripts.push(prelude + (scriptEl.textContent || ""));
1840
+ } else if (externalSrc) {
1841
+ if (!externalScriptSrcs.includes(externalSrc)) {
1842
+ externalScriptSrcs.push(externalSrc);
1843
+ }
1844
+ scriptItems.push({
1845
+ kind: "external",
1846
+ src: externalSrc,
1847
+ ...readExternalScriptAttributes(scriptEl),
1848
+ ...scene ? { scene } : {}
1849
+ });
1850
+ } else {
1851
+ const wrappedScript = scriptCompositionId ? wrapScopedCompositionScript(scriptEl.textContent || "", scriptCompositionId, scriptErrorLabel, runtimeScope || void 0, runtimeCompId || scopeCompId || scriptCompositionId, authoredRootId, src) : wrapInlineScriptWithErrorBoundary(scriptEl.textContent || "", scriptErrorLabel);
1852
+ scripts.push(wrappedScript);
1853
+ scriptItems.push({ kind: "inline", content: wrappedScript, ...scene ? { scene } : {} });
1854
+ }
1855
+ scriptEl.remove();
1856
+ }
1857
+ const assetEls = innerRoot ? innerRoot.querySelectorAll("[src], [href]") : contentDoc.querySelectorAll("[src], [href]");
1858
+ rewriteAssetPaths(assetEls, src, (el, attr) => el.getAttribute(attr), (el, attr, val) => {
1859
+ el.setAttribute(attr, val);
1860
+ }, assetExists);
1861
+ if (rewriteInlineStyles) {
1862
+ const styledEls = innerRoot ? innerRoot.querySelectorAll("[style]") : contentDoc.querySelectorAll("[style]");
1863
+ rewriteInlineStyleAssetUrls(styledEls, src, (el) => el.getAttribute("style"), (el, val) => {
1864
+ el.setAttribute("style", val);
1865
+ }, assetExists);
1866
+ }
1867
+ if (innerRoot?.hasAttribute("data-timeline-locked")) {
1868
+ hostEl.setAttribute("data-timeline-locked", "");
1869
+ }
1870
+ if (innerRoot) {
1871
+ const innerW = innerRoot.getAttribute("data-width");
1872
+ const innerH = innerRoot.getAttribute("data-height");
1873
+ if (innerW && !hostEl.getAttribute("data-width"))
1874
+ hostEl.setAttribute("data-width", innerW);
1875
+ if (innerH && !hostEl.getAttribute("data-height")) {
1876
+ hostEl.setAttribute("data-height", innerH);
1877
+ }
1878
+ }
1879
+ if (innerRoot) {
1880
+ innerRoot.setAttribute("data-composition-file", src);
1881
+ for (const child of extractedCompositionAssets(innerRoot))
1882
+ child.remove();
1883
+ if (flattenInnerRoot) {
1884
+ const prepared = flattenInnerRoot(innerRoot);
1885
+ if (!compId && scopeCompId) {
1886
+ prepared.setAttribute("data-composition-id", scopeCompId);
1887
+ }
1888
+ hostEl.innerHTML = prepared.outerHTML || "";
1889
+ } else {
1890
+ hostEl.innerHTML = compId ? innerRoot.innerHTML || "" : innerRoot.outerHTML || "";
1891
+ if (compId && authoredRootId) {
1892
+ hostEl.setAttribute("data-hf-authored-id", authoredRootId);
1893
+ }
1894
+ }
1895
+ } else {
1896
+ for (const child of extractedCompositionAssets(contentDoc))
1897
+ child.remove();
1898
+ const bodyHtml = contentDoc.body?.innerHTML || "";
1899
+ hostEl.innerHTML = bodyHtml || contentDoc.documentElement?.outerHTML || "";
1900
+ }
1901
+ for (const el of plan.inertScriptsOutsideRoot)
1902
+ hostEl.insertAdjacentHTML("beforeend", el.outerHTML);
1903
+ hostEl.setAttribute("data-composition-file", src);
1904
+ hostEl.removeAttribute("data-composition-src");
1905
+ const nestedAncestry = [...ancestry, src];
1906
+ const nested = enumerateNestedCompositionHosts(hostEl, nestedAncestry);
1907
+ for (const skipped of nested.skipped) {
1908
+ onMissingComposition?.(skipped.src, skipped.reason);
1909
+ }
1910
+ for (const nestedHost of nested.hosts) {
1911
+ queue.push({ element: nestedHost.host, ancestry: nestedAncestry, scene });
1912
+ }
1913
+ svgIdScopes.push({
1914
+ root: hostEl,
1915
+ namespace: runtimeCompId || scopeCompId,
1916
+ exclude: nested.hosts.map((nestedHost) => nestedHost.host),
1917
+ styleStart,
1918
+ styleEnd
1919
+ });
1920
+ }
1921
+ const svgIdMaps = namespaceCollidingSvgIds(document, [
1922
+ ...svgIdScopes.map(({ root, namespace, exclude, styleStart, styleEnd }) => ({
1923
+ root,
1924
+ namespace,
1925
+ exclude,
1926
+ cssTexts: styles.slice(styleStart, styleEnd).map((style) => style.css)
1927
+ })),
1928
+ {
1929
+ root: document.documentElement,
1930
+ namespace: "",
1931
+ referenceTarget: "document",
1932
+ exclude: svgIdScopes.map(({ root }) => root),
1933
+ cssTexts: rootStyles.map((style) => style.textContent ?? "")
1934
+ }
1935
+ ]);
1936
+ svgIdMaps.slice(0, svgIdScopes.length).forEach((idMap, index) => {
1937
+ const { styleStart, styleEnd } = svgIdScopes[index];
1938
+ const references = readSvgReferenceAliases(svgIdScopes[index].root, SVG_REFERENCE_ALIASES_ATTR);
1939
+ for (let i = styleStart; i < styleEnd; i += 1) {
1940
+ styles[i].css = rewriteSvgIdReferencesInCss(styles[i].css, idMap, references);
1941
+ }
1942
+ });
1943
+ const rootReferences = readSvgReferenceAliases(document.documentElement, SVG_REFERENCE_ALIASES_ATTR);
1944
+ for (const style of rootStyles) {
1945
+ style.textContent = rewriteSvgIdReferencesInCss(style.textContent ?? "", svgIdMaps[svgIdScopes.length], rootReferences);
1946
+ }
1947
+ return {
1948
+ styles,
1949
+ styleScenes,
1950
+ scripts,
1951
+ externalScriptSrcs,
1952
+ scriptItems,
1953
+ externalLinks,
1954
+ variablesByComp,
1955
+ importMaps,
1956
+ moduleScripts
1957
+ };
1958
+ }
1959
+
1960
+ // ../parsers/dist/hfIds.js
1961
+ var EXCLUDED_TAGS = /* @__PURE__ */ new Set([
1962
+ "script",
1963
+ "style",
1964
+ "template",
1965
+ "meta",
1966
+ "link",
1967
+ "noscript",
1968
+ "base"
1969
+ ]);
1970
+ function fnv1a(str) {
1971
+ let h = 2166136261;
1972
+ for (let i = 0; i < str.length; i++) {
1973
+ h ^= str.charCodeAt(i);
1974
+ h = Math.imul(h, 16777619);
1975
+ }
1976
+ return h >>> 0;
1977
+ }
1978
+ function toHfId(hash2) {
1979
+ const s = (hash2 >>> 0).toString(36);
1980
+ const four = s.length >= 4 ? s.slice(-4) : s.padStart(4, "0");
1981
+ return `hf-${four}`;
1982
+ }
1983
+ function ownText(el) {
1984
+ let text = "";
1985
+ el.childNodes.forEach((n) => {
1986
+ if (n.nodeType === 3) text += n.nodeValue ?? "";
1987
+ });
1988
+ return text.trim();
1989
+ }
1990
+ function getContractAttribute(el, name) {
1991
+ return Array.from(el.attributes).find((attr) => attr.name.toLowerCase() === name)?.value ?? null;
1992
+ }
1993
+ function contentKey(el) {
1994
+ const attrs = Array.from(el.attributes).filter((a) => !a.name.toLowerCase().startsWith("data-hf-")).map((a) => `${a.name.toLowerCase()}\0${a.value}`).sort().join("");
1995
+ return `${el.tagName.toLowerCase()}|${attrs}|${ownText(el)}`;
1996
+ }
1997
+ function mintHfId(el, assigned) {
1998
+ const key = contentKey(el);
1999
+ let id = toHfId(fnv1a(key));
2000
+ let dup = 0;
2001
+ while (assigned.has(id)) {
2002
+ dup += 1;
2003
+ if (dup > 1e4) {
2004
+ id = `hf-${(fnv1a(key) >>> 0).toString(36)}-${dup}`;
2005
+ break;
2006
+ }
2007
+ id = toHfId(fnv1a(`${key}#${dup}`));
2008
+ }
2009
+ assigned.add(id);
2010
+ return id;
2011
+ }
2012
+ function getChildElements(parent) {
2013
+ const directChildren = Array.from(parent.children);
2014
+ if (directChildren.length || parent.tagName.toLowerCase() !== "template") return directChildren;
2015
+ const content = parent.content;
2016
+ if (content?.children.length) return Array.from(content.children);
2017
+ return directChildren;
2018
+ }
2019
+ function isCompositionTemplate(el) {
2020
+ if (el.tagName.toLowerCase() !== "template") return false;
2021
+ if (getContractAttribute(el, "data-composition-id") !== null) return true;
2022
+ for (const child of getChildElements(el)) {
2023
+ if (getContractAttribute(child, "data-composition-id") !== null) return true;
2024
+ }
2025
+ return false;
2026
+ }
2027
+ function walkCompositionDescendants(root, visit) {
2028
+ const rootElement = root.nodeType === 9 ? root.documentElement : root;
2029
+ if (!rootElement) return;
2030
+ const walk = (parent) => {
2031
+ for (const child of getChildElements(parent)) {
2032
+ const isTemplate = child.tagName.toLowerCase() === "template";
2033
+ if (isTemplate && !isCompositionTemplate(child)) continue;
2034
+ visit(child);
2035
+ walk(child);
2036
+ }
2037
+ };
2038
+ walk(rootElement);
2039
+ }
2040
+ function assignHfIds(body) {
2041
+ const assigned = /* @__PURE__ */ new Set();
2042
+ walkCompositionDescendants(body, (el) => {
2043
+ const existing = getContractAttribute(el, "data-hf-id");
2044
+ if (existing) assigned.add(existing);
2045
+ });
2046
+ walkCompositionDescendants(body, (el) => {
2047
+ if (EXCLUDED_TAGS.has(el.tagName.toLowerCase())) return;
2048
+ if (getContractAttribute(el, "data-hf-id")) return;
2049
+ el.setAttribute("data-hf-id", mintHfId(el, assigned));
2050
+ });
2051
+ }
2052
+ function ensureHfIds(html) {
2053
+ const { document, wrapped } = parseFragmentOrDocument(html);
2054
+ if (!document.body) return html;
2055
+ assignHfIds(document.body);
2056
+ return wrapped ? document.body.innerHTML || "" : document.toString();
2057
+ }
2058
+ function parseFragmentOrDocument(html) {
2059
+ const wrapped = !/^(?:<!doctype|<html[\s>/])/i.test(
2060
+ html.replace(/^(?:\s|<!--(?:>|->|[\s\S]*?-->))*/, "")
2061
+ );
2062
+ const { document } = wrapped ? parseHTML(`<!DOCTYPE html><html><head></head><body>${html}</body></html>`) : parseHTML(html);
2063
+ return { document, wrapped };
2064
+ }
2065
+ function stampHfIdsInPlace(html) {
2066
+ const { document, wrapped } = parseFragmentOrDocument(html);
2067
+ if (!document.body) return html;
2068
+ const elements = wrapped ? getChildElements(document.body).flatMap(inDocumentOrder) : inDocumentOrder(document.documentElement);
2069
+ const existing = elements.map((el) => el.getAttribute("data-hf-id"));
2070
+ const pinned = existing.map((id) => id !== null && id.length > 0);
2071
+ assignHfIds(document.body);
2072
+ const minted = elements.map((el, n) => pinned[n] ? null : el.getAttribute("data-hf-id"));
2073
+ const tags = startTags(html);
2074
+ const inserts = tags && alignInserts(html, tags, elements, minted, existing);
2075
+ return inserts ? spliceIds(html, inserts) : ensureHfIds(html);
2076
+ }
2077
+ function inDocumentOrder(el) {
2078
+ return [el, ...getChildElements(el).flatMap(inDocumentOrder)];
2079
+ }
2080
+ var RAW_TEXT = /* @__PURE__ */ new Set(["script", "style", "textarea", "title", "xmp", "noembed", "noframes"]);
2081
+ var IMPLIED = /* @__PURE__ */ new Set(["html", "head", "body", "tbody"]);
2082
+ function startTags(html) {
2083
+ const tags = [];
2084
+ let i = html.indexOf("<");
2085
+ while (i >= 0) {
2086
+ const name = html.startsWith("<!--", i) ? null : /^<([a-zA-Z][^\s/>]*)/.exec(html.slice(i, i + 128));
2087
+ if (!name) {
2088
+ i = nextTagAfter(html, i);
2089
+ continue;
2090
+ }
2091
+ const end = closingBracket(html, i + name[0].length);
2092
+ if (end < 0) return null;
2093
+ const tag = name[1].toLowerCase();
2094
+ tags.push({ name: tag, nameEnd: i + name[0].length, bracket: end });
2095
+ const after = RAW_TEXT.has(tag) ? rawTextEnd(html, tag, end) : end;
2096
+ i = after < 0 ? -1 : html.indexOf("<", after + 1);
2097
+ }
2098
+ return tags;
2099
+ }
2100
+ function rawTextEnd(html, tag, from) {
2101
+ const endTag = new RegExp(`</${tag}(?=[\\s/>]|$)`, "gi");
2102
+ endTag.lastIndex = from;
2103
+ return endTag.exec(html)?.index ?? -1;
2104
+ }
2105
+ function nextTagAfter(html, lt) {
2106
+ const comment = html.startsWith("<!--", lt);
2107
+ const end = comment ? html.indexOf("-->", lt + 4) : html.indexOf(">", lt);
2108
+ return end < 0 ? -1 : html.indexOf("<", end + 1);
2109
+ }
2110
+ function closingBracket(html, from) {
2111
+ let quote = "";
2112
+ for (let i = from; i < html.length; i++) {
2113
+ const c = html[i];
2114
+ if (quote) quote = c === quote ? "" : quote;
2115
+ else if (c === '"' || c === "'") quote = c;
2116
+ else if (c === ">") return i;
2117
+ }
2118
+ return -1;
2119
+ }
2120
+ function alignInserts(html, tags, elements, minted, existing) {
2121
+ const walked = walkAlign(html, tags, elements, minted, existing);
2122
+ if (!walked) return null;
2123
+ return walked.next === tags.length ? walked.inserts : null;
2124
+ }
2125
+ function walkAlign(html, tags, elements, minted, existing) {
2126
+ const state = { inserts: [], next: 0 };
2127
+ for (const [n, el] of elements.entries()) {
2128
+ if (!take(state, html, tags, el, minted[n] ?? null, existing[n] === "")) return null;
2129
+ }
2130
+ return state;
2131
+ }
2132
+ function take(state, html, tags, el, id, fillEmpty) {
2133
+ const step = alignOne(html, tags[state.next], el, id, fillEmpty);
2134
+ if (!step) return false;
2135
+ if (step.insert) state.inserts.push(step.insert);
2136
+ if (step.next) state.next += 1;
2137
+ return true;
2138
+ }
2139
+ function alignOne(html, tag, el, id, fillEmpty) {
2140
+ if (tag?.name === el.tagName.toLowerCase()) return matched(html, tag, id, fillEmpty);
2141
+ if (IMPLIED.has(el.tagName.toLowerCase()) && !id) return { insert: null, next: false };
2142
+ return null;
2143
+ }
2144
+ function matched(html, tag, id, fillEmpty) {
2145
+ if (!id) return { insert: null, next: true };
2146
+ const placed = placeId(html, tag, id, fillEmpty);
2147
+ if (!placed) return null;
2148
+ return { insert: placed, next: true };
2149
+ }
2150
+ function placeId(html, tag, id, fillEmpty) {
2151
+ if (!fillEmpty) return { at: tag.nameEnd, text: ` data-hf-id="${id}"` };
2152
+ const emptyAt = emptyHfIdValue(html, tag);
2153
+ if (emptyAt === null) return null;
2154
+ return { at: emptyAt, text: id };
2155
+ }
2156
+ function emptyHfIdValue(html, tag) {
2157
+ const open = outsideQuotes(html.slice(tag.nameEnd, tag.bracket));
2158
+ const match = /\sdata-hf-id\s*=\s*(["'])\1/i.exec(open);
2159
+ if (!match) return null;
2160
+ return tag.nameEnd + match.index + match[0].length - 1;
2161
+ }
2162
+ function outsideQuotes(open) {
2163
+ let quote = "";
2164
+ let out = "";
2165
+ for (const c of open) {
2166
+ out += quotedChar(quote, c);
2167
+ quote = quoteOf(quote, c);
2168
+ }
2169
+ return out;
2170
+ }
2171
+ function quoteOf(quote, c) {
2172
+ if (quote) return c === quote ? "" : quote;
2173
+ return c === '"' || c === "'" ? c : "";
2174
+ }
2175
+ function quotedChar(quote, c) {
2176
+ if (!quote || c === quote) return c;
2177
+ return " ".repeat(c.length);
2178
+ }
2179
+ function spliceIds(html, inserts) {
2180
+ let out = "";
2181
+ let from = 0;
2182
+ for (const { at, text } of inserts) {
2183
+ out += html.slice(from, at) + text;
2184
+ from = at;
2185
+ }
2186
+ return out + html.slice(from);
2187
+ }
2188
+
2189
+ // ../core/dist/compiler/htmlBundler.js
2190
+ var DEFAULT_RUNTIME_SCRIPT_URL = "";
2191
+ function getRuntimeScriptUrl() {
2192
+ const configured = (process.env.HYPERFRAME_RUNTIME_URL || "").trim();
2193
+ return configured || DEFAULT_RUNTIME_SCRIPT_URL;
2194
+ }
2195
+ function injectInterceptor(html, runtimeMode = "inline") {
2196
+ const sanitized = stripEmbeddedRuntimeScripts(html);
2197
+ const runtimeScriptUrl = getRuntimeScriptUrl();
2198
+ let tag;
2199
+ if (runtimeScriptUrl) {
2200
+ const escaped = runtimeScriptUrl.replace(/"/g, "&quot;");
2201
+ tag = `<script ${RUNTIME_BOOTSTRAP_ATTR}="1" src="${escaped}"></script>`;
2202
+ } else if (runtimeMode === "placeholder") {
2203
+ tag = `<script ${RUNTIME_BOOTSTRAP_ATTR}="1" src=""></script>`;
2204
+ } else {
2205
+ const inlinedRuntime = getHyperframeRuntimeScript();
2206
+ tag = `<script ${RUNTIME_BOOTSTRAP_ATTR}="1">${inlinedRuntime}</script>`;
2207
+ }
2208
+ return insertRuntimeTag(sanitized, tag);
2209
+ }
2210
+ function isRelativeUrl(url) {
2211
+ return !isNonRelativeUrl(url) && !isAbsolute(url);
2212
+ }
2213
+ var bundleReads = new AsyncLocalStorage();
2214
+ function noteRead(filePath) {
2215
+ bundleReads.getStore()?.(filePath);
2216
+ }
2217
+ function safeReadFile(filePath) {
2218
+ noteRead(filePath);
2219
+ if (!existsSync(filePath))
2220
+ return null;
2221
+ try {
2222
+ return readFileSync(filePath, "utf-8");
2223
+ } catch {
2224
+ return null;
2225
+ }
2226
+ }
2227
+ var CSS_IMPORT_RE = /@import\s+(?:url\(\s*(["']?)([^)"']+)\1\s*\)|(["'])([^"']+)\3)\s*([^;]*);\s*/g;
2228
+ var CSS_COMMENT_RE = /\/\*[\s\S]*?\*\//g;
2229
+ function withCommentsStripped(css, fn) {
2230
+ const comments = [];
2231
+ const stripped = css.replace(CSS_COMMENT_RE, (m) => {
2232
+ const idx = comments.length;
2233
+ comments.push(m);
2234
+ return `/*__hf_c${idx}__*/`;
2235
+ });
2236
+ const result = fn(stripped);
2237
+ const restore = (s) => {
2238
+ let out = s;
2239
+ for (let i = 0; i < comments.length; i++) {
2240
+ out = out.replace(`/*__hf_c${i}__*/`, comments[i]);
2241
+ }
2242
+ return out;
2243
+ };
2244
+ return { result, restore };
2245
+ }
2246
+ function resolveRelativeUrlPath(fromDir, basePath) {
2247
+ return resolve2(fromDir, decodeWellFormedEscapes(basePath.replaceAll("\\", "/")));
2248
+ }
2249
+ function rebaseCssUrls(css, cssFileDir, projectDir) {
2250
+ const resolvedRoot = resolve2(projectDir);
2251
+ const resolvedDir = resolve2(cssFileDir);
2252
+ if (resolvedDir === resolvedRoot)
2253
+ return css;
2254
+ return css.replace(CSS_URL_RE, (full, quote, urlValue) => {
2255
+ const decoded = decodeCssEscapes(urlValue);
2256
+ if (!decoded || !isRelativeUrl(decoded))
2257
+ return full;
2258
+ const { basePath, suffix } = splitUrlSuffix(decoded);
2259
+ if (!basePath)
2260
+ return full;
2261
+ const absolutePath = resolveRelativeUrlPath(resolvedDir, basePath);
2262
+ const rebased = encodeUrlPath(relative(resolvedRoot, absolutePath).split(sep).join("/"));
2263
+ if (rebased === basePath)
2264
+ return full;
2265
+ const escapedSuffix = suffix.replace(/[\s\p{Cc}"'()\\<>]/gu, (char) => `\\${char.codePointAt(0).toString(16).padStart(6, "0")}`);
2266
+ return `url(${quote || ""}${rebased}${escapedSuffix}${quote || ""})`;
2267
+ });
2268
+ }
2269
+ function rebaseRelativePath(urlValue, fromDir, toDir) {
2270
+ const { basePath, suffix } = splitUrlSuffix(urlValue.trim());
2271
+ if (!basePath)
2272
+ return urlValue;
2273
+ const absolutePath = resolveRelativeUrlPath(fromDir, basePath);
2274
+ const rebased = encodeUrlPath(relative(resolve2(toDir), absolutePath).split(sep).join("/"));
2275
+ return appendSuffixToUrl(rebased, suffix);
2276
+ }
2277
+ function rewriteSrcsetUrls(srcset, rewriteUrl) {
2278
+ const parts = [];
2279
+ let position = 0;
2280
+ let written = 0;
2281
+ while (position < srcset.length) {
2282
+ while (position < srcset.length && /[ \t\n\r\f,]/.test(srcset.charAt(position)))
2283
+ position++;
2284
+ const start = position;
2285
+ while (position < srcset.length && !/[ \t\n\r\f]/.test(srcset.charAt(position)))
2286
+ position++;
2287
+ let end = position;
2288
+ while (end > start && srcset.charAt(end - 1) === ",")
2289
+ end--;
2290
+ if (end > start) {
2291
+ const url = srcset.slice(start, end);
2292
+ const rewritten = rewriteUrl(url);
2293
+ if (rewritten !== url) {
2294
+ parts.push(srcset.slice(written, start), rewritten);
2295
+ written = end;
2296
+ }
2297
+ }
2298
+ if (end < position)
2299
+ continue;
2300
+ let inParens = false;
2301
+ while (position < srcset.length) {
2302
+ const char = srcset.charAt(position++);
2303
+ if (char === "(")
2304
+ inParens = true;
2305
+ else if (char === ")")
2306
+ inParens = false;
2307
+ else if (char === "," && !inParens)
2308
+ break;
2309
+ }
2310
+ }
2311
+ return parts.length > 0 ? parts.join("") + srcset.slice(written) : srcset;
2312
+ }
2313
+ function rebaseColorGradingLutPath(value, fromDir, toDir) {
2314
+ if (!value.trim().startsWith("{"))
2315
+ return value;
2316
+ let parsed;
2317
+ try {
2318
+ parsed = JSON.parse(value);
2319
+ } catch {
2320
+ return value;
2321
+ }
2322
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed))
2323
+ return value;
2324
+ const lut = Reflect.get(parsed, "lut");
2325
+ if (typeof lut === "string") {
2326
+ if (!isRelativeUrl(lut))
2327
+ return value;
2328
+ Reflect.set(parsed, "lut", rebaseRelativePath(lut, fromDir, toDir));
2329
+ return JSON.stringify(parsed);
2330
+ }
2331
+ if (typeof lut !== "object" || lut === null || Array.isArray(lut))
2332
+ return value;
2333
+ const lutSrc = Reflect.get(lut, "src");
2334
+ if (typeof lutSrc !== "string" || !isRelativeUrl(lutSrc))
2335
+ return value;
2336
+ Reflect.set(lut, "src", rebaseRelativePath(lutSrc, fromDir, toDir));
2337
+ return JSON.stringify(parsed);
2338
+ }
2339
+ function rebaseEntryAuthoredAssetPaths(document, sourceDir, projectDir) {
2340
+ for (const styleEl of [...document.querySelectorAll("style")]) {
2341
+ styleEl.textContent = rebaseCssUrls(styleEl.textContent || "", sourceDir, projectDir);
2342
+ }
2343
+ for (const el of [...document.querySelectorAll("[style]")]) {
2344
+ const styleAttr = el.getAttribute("style");
2345
+ if (styleAttr)
2346
+ el.setAttribute("style", rebaseCssUrls(styleAttr, sourceDir, projectDir));
2347
+ }
2348
+ for (const el of [...document.querySelectorAll("[src], [href], [poster], [xlink\\:href]")]) {
2349
+ if (el.tagName === "LINK" && (el.getAttribute("rel") || "").toLowerCase() === "stylesheet")
2350
+ continue;
2351
+ if (el.tagName === "SCRIPT" && el.hasAttribute("src"))
2352
+ continue;
2353
+ for (const attr of ["src", "href", "poster", "xlink:href"]) {
2354
+ const value = el.getAttribute(attr);
2355
+ if (!value || !isRelativeUrl(value))
2356
+ continue;
2357
+ el.setAttribute(attr, rebaseRelativePath(value, sourceDir, projectDir));
2358
+ }
2359
+ }
2360
+ for (const el of [...document.querySelectorAll("[srcset]")]) {
2361
+ const srcset = el.getAttribute("srcset");
2362
+ if (srcset)
2363
+ el.setAttribute("srcset", rewriteSrcsetUrls(srcset, (url) => isRelativeUrl(url) ? rebaseRelativePath(url, sourceDir, projectDir) : url));
2364
+ }
2365
+ for (const el of [...document.querySelectorAll(`[${HF_COLOR_GRADING_ATTR}]`)]) {
2366
+ const value = el.getAttribute(HF_COLOR_GRADING_ATTR);
2367
+ if (value)
2368
+ el.setAttribute(HF_COLOR_GRADING_ATTR, rebaseColorGradingLutPath(value, sourceDir, projectDir));
2369
+ }
2370
+ }
2371
+ function inlineCssFile(css, cssFileDir, projectDir, activeImports) {
2372
+ const { result: strippedCss, restore: restoreComments } = withCommentsStripped(css, (s) => s);
2373
+ const importPlaceholders = [];
2374
+ const withPlaceholders = strippedCss.replace(CSS_IMPORT_RE, (full, _q1, urlPath, _q2, barePath, mediaQuery) => {
2375
+ const importPath = urlPath ?? barePath;
2376
+ if (!importPath || !isRelativeUrl(importPath))
2377
+ return full;
2378
+ const resolved = resolve2(cssFileDir, decodedUrlPath(importPath));
2379
+ if (!isSafePath(projectDir, resolved))
2380
+ return full;
2381
+ if (activeImports.has(resolved))
2382
+ return "";
2383
+ const content = safeReadFile(resolved);
2384
+ if (content == null)
2385
+ return full;
2386
+ activeImports.add(resolved);
2387
+ const inlined = inlineCssFile(content, dirname(resolved), projectDir, activeImports);
2388
+ activeImports.delete(resolved);
2389
+ const trimmedMedia = (mediaQuery || "").trim();
2390
+ const block = trimmedMedia ? `@media ${trimmedMedia} {
2391
+ ${inlined}
2392
+ }
2393
+ ` : inlined + "\n";
2394
+ const idx = importPlaceholders.length;
2395
+ importPlaceholders.push(block);
2396
+ return `/*__hf_import_${idx}__*/`;
2397
+ });
2398
+ let rebased = rebaseCssUrls(withPlaceholders, cssFileDir, projectDir);
2399
+ rebased = restoreComments(rebased);
2400
+ for (let i = 0; i < importPlaceholders.length; i++) {
2401
+ rebased = rebased.replace(`/*__hf_import_${i}__*/`, importPlaceholders[i]);
2402
+ }
2403
+ return rebased;
2404
+ }
2405
+ function safeReadFileBuffer(filePath) {
2406
+ noteRead(filePath);
2407
+ if (!existsSync(filePath))
2408
+ return null;
2409
+ try {
2410
+ return readFileSync(filePath);
2411
+ } catch {
2412
+ return null;
2413
+ }
2414
+ }
2415
+ function appendSuffixToUrl(baseUrl, suffix) {
2416
+ if (!suffix)
2417
+ return baseUrl;
2418
+ if (suffix.startsWith("#"))
2419
+ return `${baseUrl}${suffix}`;
2420
+ if (suffix.startsWith("?")) {
2421
+ const queryWithOptionalHash = suffix.slice(1);
2422
+ if (!queryWithOptionalHash)
2423
+ return baseUrl;
2424
+ const hashIdx = queryWithOptionalHash.indexOf("#");
2425
+ const queryPart = hashIdx >= 0 ? queryWithOptionalHash.slice(0, hashIdx) : queryWithOptionalHash;
2426
+ const hashPart = hashIdx >= 0 ? queryWithOptionalHash.slice(hashIdx) : "";
2427
+ if (!queryPart)
2428
+ return `${baseUrl}${hashPart}`;
2429
+ const joiner = baseUrl.includes("?") ? "&" : "?";
2430
+ return `${baseUrl}${joiner}${queryPart}${hashPart}`;
2431
+ }
2432
+ return baseUrl;
2433
+ }
2434
+ var INLINE_MIME = {
2435
+ ".svg": "image/svg+xml",
2436
+ ".json": "application/json",
2437
+ ".txt": "text/plain",
2438
+ ".cube": "text/plain",
2439
+ ".xml": "application/xml",
2440
+ // Fonts and raster images. A bundle handed to a consumer that stores it as a
2441
+ // lone object — no sibling `assets/` directory — 404s on every surviving
2442
+ // relative reference, and a missing font silently reflows the whole frame
2443
+ // rather than failing loudly. Media (mp4/webm/mp3/wav) is deliberately absent:
2444
+ // it is large, streamed rather than laid out, and its absence is obvious.
2445
+ ".woff2": "font/woff2",
2446
+ ".woff": "font/woff",
2447
+ ".ttf": "font/ttf",
2448
+ ".otf": "font/otf",
2449
+ ".png": "image/png",
2450
+ ".jpg": "image/jpeg",
2451
+ ".jpeg": "image/jpeg",
2452
+ ".gif": "image/gif",
2453
+ ".webp": "image/webp",
2454
+ ".avif": "image/avif"
2455
+ };
2456
+ var MAX_INLINE_ASSET_BYTES = 2 * 1024 * 1024;
2457
+ var MAX_INLINED_BUNDLE_CHARS = 256 * 1024 * 1024;
2458
+ function safeStatSize(filePath) {
2459
+ try {
2460
+ return statSync(filePath).size;
2461
+ } catch {
2462
+ return null;
2463
+ }
2464
+ }
2465
+ function warnAssetTooLargeToInline(assetPath, byteLength) {
2466
+ const mb = (byteLength / (1024 * 1024)).toFixed(1);
2467
+ console.warn(`[Framey] Not inlining "${assetPath}" (${mb} MB exceeds the ${MAX_INLINE_ASSET_BYTES / (1024 * 1024)} MB inline limit). The bundle may not be self-contained.`);
2468
+ }
2469
+ function warnInlineBudgetExhausted(assetPath) {
2470
+ console.warn(`[Framey] Not inlining "${assetPath}" and later assets: the bundle already inlines ${MAX_INLINED_BUNDLE_CHARS / (1024 * 1024)} MB of data URLs. The bundle may not be self-contained.`);
2471
+ }
2472
+ function createAssetInliner(resolveProjectPath, inlineAssets) {
2473
+ const assets = /* @__PURE__ */ new Map();
2474
+ let inlinedChars = 0;
2475
+ let budgetExhausted = false;
2476
+ const readAsset = (filePath, mimeType) => {
2477
+ const byteLength = safeStatSize(filePath);
2478
+ if (byteLength !== null && byteLength > MAX_INLINE_ASSET_BYTES)
2479
+ return { tooLarge: byteLength };
2480
+ const content = safeReadFileBuffer(filePath);
2481
+ return {
2482
+ dataUrl: content === null ? null : `data:${mimeType};base64,${content.toString("base64")}`
2483
+ };
2484
+ };
2485
+ return (urlValue) => {
2486
+ if (!inlineAssets)
2487
+ return null;
2488
+ if (!urlValue || !isRelativeUrl(urlValue))
2489
+ return null;
2490
+ const { basePath, suffix } = splitUrlSuffix(urlValue.trim());
2491
+ if (!basePath)
2492
+ return null;
2493
+ const filePath = resolveProjectPath(decodeWellFormedEscapes(basePath));
2494
+ if (!filePath)
2495
+ return null;
2496
+ const ext = filePath.toLowerCase().match(/\.[^.]+$/)?.[0] ?? "";
2497
+ const mimeType = INLINE_MIME[ext];
2498
+ if (!mimeType)
2499
+ return null;
2500
+ let asset = assets.get(filePath);
2501
+ if (asset === void 0) {
2502
+ asset = readAsset(filePath, mimeType);
2503
+ assets.set(filePath, asset);
2504
+ } else if ("dataUrl" in asset) {
2505
+ noteRead(filePath);
2506
+ }
2507
+ if ("tooLarge" in asset) {
2508
+ warnAssetTooLargeToInline(basePath, asset.tooLarge);
2509
+ return null;
2510
+ }
2511
+ if (asset.dataUrl === null)
2512
+ return null;
2513
+ if (budgetExhausted || inlinedChars + asset.dataUrl.length > MAX_INLINED_BUNDLE_CHARS) {
2514
+ if (!budgetExhausted)
2515
+ warnInlineBudgetExhausted(basePath);
2516
+ budgetExhausted = true;
2517
+ return null;
2518
+ }
2519
+ inlinedChars += asset.dataUrl.length;
2520
+ const hashIdx = suffix.indexOf("#");
2521
+ return hashIdx < 0 ? asset.dataUrl : `${asset.dataUrl}${suffix.slice(hashIdx)}`;
2522
+ };
2523
+ }
2524
+ function isExternalSvgFragmentUse(el, attr, urlValue) {
2525
+ if (el.tagName.toLowerCase() !== "use")
2526
+ return false;
2527
+ if (attr !== "href" && attr !== "xlink:href")
2528
+ return false;
2529
+ if (!isRelativeUrl(urlValue))
2530
+ return false;
2531
+ const hashIdx = urlValue.indexOf("#");
2532
+ if (hashIdx <= 0)
2533
+ return false;
2534
+ const pathBeforeFragment = urlValue.slice(0, hashIdx).split("?", 1)[0] ?? "";
2535
+ return pathBeforeFragment.toLowerCase().endsWith(".svg");
2536
+ }
2537
+ function warnColorGradingLutNotInlined(lutSrc) {
2538
+ const trimmed = lutSrc.trim();
2539
+ if (!isRelativeUrl(trimmed))
2540
+ return;
2541
+ console.warn(`[Framey] Could not inline color grading LUT "${trimmed}". The rendered bundle may not be self-contained.`);
2542
+ }
2543
+ function rewriteColorGradingLutWithInlinedAssets(value, inlineAsset) {
2544
+ if (!value.trim().startsWith("{"))
2545
+ return value;
2546
+ let parsed;
2547
+ try {
2548
+ parsed = JSON.parse(value);
2549
+ } catch {
2550
+ return value;
2551
+ }
2552
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed))
2553
+ return value;
2554
+ const lut = Reflect.get(parsed, "lut");
2555
+ if (typeof lut === "string") {
2556
+ const inlined2 = inlineAsset(lut);
2557
+ if (!inlined2) {
2558
+ warnColorGradingLutNotInlined(lut);
2559
+ return value;
2560
+ }
2561
+ Reflect.set(parsed, "lut", inlined2);
2562
+ return JSON.stringify(parsed);
2563
+ }
2564
+ if (typeof lut !== "object" || lut === null || Array.isArray(lut))
2565
+ return value;
2566
+ const lutSrc = Reflect.get(lut, "src");
2567
+ if (typeof lutSrc !== "string")
2568
+ return value;
2569
+ const inlined = inlineAsset(lutSrc);
2570
+ if (!inlined) {
2571
+ warnColorGradingLutNotInlined(lutSrc);
2572
+ return value;
2573
+ }
2574
+ Reflect.set(lut, "src", inlined);
2575
+ return JSON.stringify(parsed);
2576
+ }
2577
+ function rewriteCssUrlsWithInlinedAssets(cssText, inlineAsset) {
2578
+ if (!cssText)
2579
+ return cssText;
2580
+ return cssText.replace(/\burl\(\s*(["']?)([^)"']+)\1\s*\)/g, (_full, quote, rawUrl) => {
2581
+ const maybeInlined = inlineAsset((rawUrl || "").trim());
2582
+ if (!maybeInlined)
2583
+ return _full;
2584
+ return `url(${quote || ""}${maybeInlined}${quote || ""})`;
2585
+ });
2586
+ }
2587
+ function cssAttributeSelector(attr, value) {
2588
+ const escaped = value.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/</g, "\\3c ");
2589
+ return `[${attr}="${escaped}"]`;
2590
+ }
2591
+ function uniqueCompositionId(baseId, index) {
2592
+ return `${baseId}__hf${index}`;
2593
+ }
2594
+ function getBundledHostCompositionIdentity(host) {
2595
+ const currentCompositionId = (host.getAttribute("data-composition-id") || "").trim() || null;
2596
+ const authoredCompositionId = (host.getAttribute("data-hf-original-composition-id") || currentCompositionId || "").trim() || null;
2597
+ return {
2598
+ authoredCompositionId,
2599
+ runtimeCompositionId: currentCompositionId
2600
+ };
2601
+ }
2602
+ function getBundledTrackedCompositionHosts(document) {
2603
+ const hosts = Array.from(document.querySelectorAll("[data-composition-src], [data-composition-id]"));
2604
+ return hosts.filter((host) => {
2605
+ if (host.hasAttribute("data-composition-src"))
2606
+ return true;
2607
+ const authoredCompositionId = getBundledHostCompositionIdentity(host).authoredCompositionId;
2608
+ if (!authoredCompositionId)
2609
+ return false;
2610
+ return !!document.getElementById(`${authoredCompositionId}-template`);
2611
+ });
2612
+ }
2613
+ function shouldAssignBundledRuntimeCompositionId(host, document) {
2614
+ if (host.hasAttribute("data-composition-src"))
2615
+ return true;
2616
+ const authoredCompositionId = getBundledHostCompositionIdentity(host).authoredCompositionId;
2617
+ if (!authoredCompositionId)
2618
+ return false;
2619
+ if (!document.getElementById(`${authoredCompositionId}-template`))
2620
+ return false;
2621
+ return host.children.length === 0;
2622
+ }
2623
+ function countBundledAuthoredCompositionIds(hosts) {
2624
+ const counts = /* @__PURE__ */ new Map();
2625
+ for (const host of hosts) {
2626
+ const authoredCompositionId = getBundledHostCompositionIdentity(host).authoredCompositionId;
2627
+ if (!authoredCompositionId)
2628
+ continue;
2629
+ counts.set(authoredCompositionId, (counts.get(authoredCompositionId) || 0) + 1);
2630
+ }
2631
+ countPageRoot(counts, hosts);
2632
+ return counts;
2633
+ }
2634
+ function assignBundledRuntimeCompositionIds(hosts, counts = countBundledAuthoredCompositionIds(hosts)) {
2635
+ const instanceByCompositionId = /* @__PURE__ */ new Map();
2636
+ const identities = /* @__PURE__ */ new Map();
2637
+ for (const host of hosts) {
2638
+ const { authoredCompositionId, runtimeCompositionId: previousRuntimeCompositionId } = getBundledHostCompositionIdentity(host);
2639
+ const shouldAssign = shouldAssignBundledRuntimeCompositionId(host, host.ownerDocument);
2640
+ if (!authoredCompositionId) {
2641
+ identities.set(host, {
2642
+ authoredCompositionId: null,
2643
+ runtimeCompositionId: previousRuntimeCompositionId
2644
+ });
2645
+ continue;
2646
+ }
2647
+ const duplicateInstance = (counts.get(authoredCompositionId) || 0) > 1;
2648
+ let runtimeCompositionId = previousRuntimeCompositionId || authoredCompositionId;
2649
+ if (shouldAssign) {
2650
+ const instanceIndex = duplicateInstance ? (instanceByCompositionId.get(authoredCompositionId) || 0) + 1 : 0;
2651
+ if (duplicateInstance) {
2652
+ instanceByCompositionId.set(authoredCompositionId, instanceIndex);
2653
+ host.setAttribute("data-hf-original-composition-id", authoredCompositionId);
2654
+ } else {
2655
+ host.removeAttribute("data-hf-original-composition-id");
2656
+ }
2657
+ runtimeCompositionId = duplicateInstance ? uniqueCompositionId(authoredCompositionId, instanceIndex) : authoredCompositionId;
2658
+ host.setAttribute("data-composition-id", runtimeCompositionId);
2659
+ }
2660
+ identities.set(host, {
2661
+ authoredCompositionId,
2662
+ runtimeCompositionId
2663
+ });
2664
+ }
2665
+ return identities;
2666
+ }
2667
+ function prepareFlattenedInnerRoot(innerRoot) {
2668
+ const prepared = innerRoot.cloneNode(true);
2669
+ markFlattenedInnerRoot(prepared);
2670
+ const w = prepared.getAttribute("data-width");
2671
+ const h = prepared.getAttribute("data-height");
2672
+ const widthVal = w ? `${w}px` : "100%";
2673
+ const heightVal = h ? `${h}px` : "100%";
2674
+ const existingStyle = (prepared.getAttribute("style") || "").trim();
2675
+ const fill = `width:${widthVal};height:${heightVal}`;
2676
+ prepared.setAttribute("style", existingStyle ? `${existingStyle};${fill}` : fill);
2677
+ return prepared;
2678
+ }
2679
+ function enforceCompositionPixelSizing(document) {
2680
+ const compositionEls = [
2681
+ ...document.querySelectorAll("[data-composition-id][data-width][data-height]")
2682
+ ];
2683
+ if (compositionEls.length === 0)
2684
+ return;
2685
+ const sizeMap = /* @__PURE__ */ new Map();
2686
+ for (const el of compositionEls) {
2687
+ const compId = el.getAttribute("data-composition-id");
2688
+ const w = Number(el.getAttribute("data-width"));
2689
+ const h = Number(el.getAttribute("data-height"));
2690
+ if (compId && Number.isFinite(w) && Number.isFinite(h) && w > 0 && h > 0) {
2691
+ sizeMap.set(compId, { w, h });
2692
+ }
2693
+ }
2694
+ if (sizeMap.size === 0)
2695
+ return;
2696
+ for (const styleEl of document.querySelectorAll("style")) {
2697
+ let css = styleEl.textContent || "";
2698
+ let modified = false;
2699
+ for (const [compId, { w, h }] of sizeMap) {
2700
+ const escaped = compId.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2701
+ const blockRe = new RegExp(`(\\[data-composition-id=["']${escaped}["']\\]\\s*\\{)([^}]*)(})`, "g");
2702
+ css = css.replace(blockRe, (_, open, body, close) => {
2703
+ const newBody = body.replace(/(\bwidth\s*:\s*)100%/g, `$1${w}px`).replace(/(\bheight\s*:\s*)100%/g, `$1${h}px`);
2704
+ if (newBody !== body)
2705
+ modified = true;
2706
+ return open + newBody + close;
2707
+ });
2708
+ }
2709
+ if (modified)
2710
+ styleEl.textContent = css;
2711
+ }
2712
+ }
2713
+ function autoHealMissingCompositionIds(document) {
2714
+ const compositionIdRe = /data-composition-id=["']([^"']+)["']/gi;
2715
+ const referencedIds = /* @__PURE__ */ new Set();
2716
+ for (const el of document.querySelectorAll("style, script")) {
2717
+ const text = (el.textContent || "").trim();
2718
+ if (!text)
2719
+ continue;
2720
+ let match;
2721
+ while ((match = compositionIdRe.exec(text)) !== null) {
2722
+ const compId = (match[1] || "").trim();
2723
+ if (compId)
2724
+ referencedIds.add(compId);
2725
+ }
2726
+ }
2727
+ if (referencedIds.size === 0)
2728
+ return;
2729
+ const existingIds = /* @__PURE__ */ new Set();
2730
+ for (const el of document.querySelectorAll("[data-composition-id]")) {
2731
+ const id = (el.getAttribute("data-composition-id") || "").trim();
2732
+ if (id)
2733
+ existingIds.add(id);
2734
+ }
2735
+ for (const compId of referencedIds) {
2736
+ if (compId === "root" || existingIds.has(compId))
2737
+ continue;
2738
+ const candidates = [`${compId}-layer`, `${compId}-comp`, compId];
2739
+ for (const targetId of candidates) {
2740
+ const found = document.getElementById(targetId);
2741
+ if (found && !found.getAttribute("data-composition-id")) {
2742
+ found.setAttribute("data-composition-id", compId);
2743
+ break;
2744
+ }
2745
+ }
2746
+ }
2747
+ }
2748
+ function joinCssHoistingImports(sheets) {
2749
+ const imports = /* @__PURE__ */ new Set();
2750
+ const cssParts = [];
2751
+ for (const sheet of sheets) {
2752
+ const rest = sheet.trim().replace(CSS_IMPORT_RE, (match) => {
2753
+ imports.add(match.trim());
2754
+ return "";
2755
+ });
2756
+ if (rest.trim())
2757
+ cssParts.push(rest.trim());
2758
+ }
2759
+ return [...imports, ...cssParts].join("\n\n").trim();
2760
+ }
2761
+ function placeSceneStylesLikeRender(document) {
2762
+ const styles = [...document.querySelectorAll("head style")];
2763
+ const imports = /* @__PURE__ */ new Set();
2764
+ for (const el of styles) {
2765
+ el.textContent = (el.textContent || "").replace(CSS_IMPORT_RE, (match) => (imports.add(match.trim()), "")).trim();
2766
+ }
2767
+ styles.slice(1).reduce((previous, el) => (previous.after(el), el), styles[0]);
2768
+ if (imports.size === 0)
2769
+ return;
2770
+ const hoisted = [...imports].join("\n\n");
2771
+ const first = styles[0];
2772
+ if (!first.hasAttribute(SCENE_PART_ATTR)) {
2773
+ first.textContent = [hoisted, first.textContent].filter(Boolean).join("\n\n");
2774
+ return;
2775
+ }
2776
+ const holder = document.createElement("style");
2777
+ holder.textContent = hoisted;
2778
+ first.before(holder);
2779
+ }
2780
+ function isAlwaysAppliedStyle(el) {
2781
+ return cssStyleMergeKey(el) === UNCONDITIONAL_CSS_KEY && !el.closest("template, noscript, svg");
2782
+ }
2783
+ function pushRun(runs, scene, chunk) {
2784
+ const last = runs.at(-1);
2785
+ if (last && last.scene === scene)
2786
+ last.chunks.push(chunk);
2787
+ else
2788
+ runs.push({ scene, chunks: [chunk] });
2789
+ }
2790
+ async function coalesceHeadStylesAndBodyScripts(document, provenance) {
2791
+ const allHeadStyles = [...document.querySelectorAll("head style")];
2792
+ const isScenePart = (el) => el.hasAttribute(SCENE_PART_ATTR);
2793
+ for (const run of allHeadStyles.length > 1 ? headStyleRuns(allHeadStyles, isScenePart) : []) {
2794
+ const merged = joinCssHoistingImports(run.map((el) => el.textContent || ""));
2795
+ if (!merged)
2796
+ continue;
2797
+ run[0].textContent = merged;
2798
+ for (const el of run.slice(1))
2799
+ el.remove();
2800
+ }
2801
+ if (allHeadStyles.some(isScenePart))
2802
+ placeSceneStylesLikeRender(document);
2803
+ const isPinned = (el) => el.hasAttribute(RUNTIME_BOOTSTRAP_ATTR) || el.hasAttribute(SCENE_PART_ATTR);
2804
+ for (const { members, anchor } of inlineScriptRuns([...document.querySelectorAll("body script")], isPinned)) {
2805
+ const mergedJs = joinJsChunks(members.map((el) => el.textContent || ""));
2806
+ if (mergedJs && !parsesAsScript(mergedJs)) {
2807
+ for (const el of members)
2808
+ el.textContent = await inlineScriptSource(el.textContent || "", provenance);
2809
+ continue;
2810
+ }
2811
+ for (const el of members)
2812
+ el.remove();
2813
+ if (!mergedJs)
2814
+ continue;
2815
+ const inlineScript = document.createElement("script");
2816
+ inlineScript.textContent = await inlineScriptSource(mergedJs, provenance);
2817
+ if (anchor)
2818
+ anchor.before(inlineScript);
2819
+ else
2820
+ document.body.appendChild(inlineScript);
2821
+ }
2822
+ }
2823
+ function injectTextRenderingRule(document) {
2824
+ const head = document.head;
2825
+ if (!head)
2826
+ return;
2827
+ if (document.querySelector("style[data-hyperframes-text-rendering]"))
2828
+ return;
2829
+ const styleEl = document.createElement("style");
2830
+ styleEl.setAttribute("data-hyperframes-text-rendering", "true");
2831
+ styleEl.textContent = "html,body,*{text-rendering:geometricPrecision}";
2832
+ head.insertBefore(styleEl, head.firstChild);
2833
+ }
2834
+ function joinJsChunks(chunks) {
2835
+ return chunks.map((chunk) => chunk.trim()).filter((chunk) => chunk.length > 0).map((chunk) => chunk.endsWith(";") ? chunk : chunk + "\n;").join("\n");
2836
+ }
2837
+ function parsesAsScript(source) {
2838
+ try {
2839
+ parseJs(source, { ecmaVersion: "latest", sourceType: "script" });
2840
+ return true;
2841
+ } catch {
2842
+ return false;
2843
+ }
2844
+ }
2845
+ async function stripJsCommentsParserSafe(source, provenance) {
2846
+ if (!source)
2847
+ return source;
2848
+ const { transform } = await import("esbuild");
2849
+ try {
2850
+ const result = await transform(source, {
2851
+ loader: "js",
2852
+ minify: false,
2853
+ legalComments: "none",
2854
+ ...provenance ? { sourcemap: "external", sourcefile: "hf-authored-bundle.js" } : {}
2855
+ });
2856
+ if (provenance) {
2857
+ const sourceURL = `hf-inspect-${createHash("sha256").update(source).digest("hex")}.js`;
2858
+ provenance({ input: source, output: result.code.trim(), sourceMap: result.map, sourceURL });
2859
+ return `${result.code.trim()}
2860
+ //# sourceURL=${sourceURL}`;
2861
+ }
2862
+ return result.code.trim();
2863
+ } catch {
2864
+ return source;
2865
+ }
2866
+ }
2867
+ async function inlineScriptSource(js, provenance) {
2868
+ return escapeInlineScriptSource(await stripJsCommentsParserSafe(js, provenance));
2869
+ }
2870
+ function preserveLocalScriptIntegrity(doc, src, resolvePath) {
2871
+ const path = resolvePath(src);
2872
+ if (!path)
2873
+ return false;
2874
+ const pinned = [...doc.querySelectorAll("script[src][integrity]")].filter((el) => {
2875
+ const candidate = el.getAttribute("src") || "";
2876
+ return isRelativeUrl(candidate) && resolvePath(candidate) === path && el.getAttribute("integrity")?.trim();
2877
+ });
2878
+ for (const el of pinned)
2879
+ ensureExternalScriptTag(doc, src, readExternalScriptAttributes(el));
2880
+ return pinned.length > 0;
2881
+ }
2882
+ function hoistExternalScript(src, projectDir, doc, seenSrcs, chunks, attributes) {
2883
+ if (attributes.integrity?.trim()) {
2884
+ ensureExternalScriptTag(doc, src, attributes);
2885
+ seenSrcs.add(src);
2886
+ return;
2887
+ }
2888
+ if (seenSrcs.has(src))
2889
+ return;
2890
+ seenSrcs.add(src);
2891
+ if (!isNonRelativeUrl(src) && !isAbsolute(src) && attributes.type !== "module") {
2892
+ const jsPath = resolveWithinProject(projectDir, decodedUrlPath(src));
2893
+ const js = jsPath ? safeReadFile(jsPath) : null;
2894
+ if (js != null) {
2895
+ chunks.push(() => preserveLocalScriptIntegrity(doc, src, (value) => resolveWithinProject(projectDir, decodedUrlPath(value))) ? "" : js);
2896
+ return;
2897
+ }
2898
+ }
2899
+ ensureExternalScriptTag(doc, src, attributes);
2900
+ }
2901
+ function hoistCompositionScripts(container, opts) {
2902
+ for (const scriptEl of executableScripts(container)) {
2903
+ const externalSrc = (scriptEl.getAttribute("src") || "").trim();
2904
+ const type = (scriptEl.getAttribute("type") || "").trim().toLowerCase();
2905
+ if (!externalSrc && type === "importmap") {
2906
+ const map = parseImportMap(scriptEl.textContent || "", (url) => url);
2907
+ if (map)
2908
+ opts.importMaps.push(map);
2909
+ else
2910
+ console.warn(`[Framey] ${opts.compId}: import map is not valid JSON, so it is skipped.`);
2911
+ } else if (!externalSrc && type === "module") {
2912
+ const prelude = opts.compId ? scopedModulePrelude(opts.runtimeCompId || opts.compId) : "";
2913
+ opts.moduleScripts.push(prelude + (scriptEl.textContent || ""));
2914
+ } else if (externalSrc) {
2915
+ hoistExternalScript(externalSrc, opts.projectDir, opts.document, opts.seenCompScriptSrcs, opts.compScriptChunks, readExternalScriptAttributes(scriptEl));
2916
+ } else {
2917
+ opts.compScriptChunks.push(opts.compId ? wrapScopedCompositionScript(scriptEl.textContent || "", opts.compId, "[Framey] composition script error:", opts.runtimeScope, opts.runtimeCompId || opts.compId, opts.authoredRootId) : wrapInlineScriptWithErrorBoundary(scriptEl.textContent || "", "[Framey] composition script error:"));
2918
+ }
2919
+ scriptEl.remove();
2920
+ }
2921
+ }
2922
+ function bundleToSingleHtml(projectDir, options) {
2923
+ const bundle = () => bundleProject(projectDir, options);
2924
+ const onRead = options?.onRead;
2925
+ if (!onRead)
2926
+ return bundle();
2927
+ const noted = /* @__PURE__ */ new Set();
2928
+ const noteOnce = (filePath) => {
2929
+ if (noted.has(filePath))
2930
+ return;
2931
+ noted.add(filePath);
2932
+ onRead(filePath);
2933
+ };
2934
+ return bundleReads.run(noteOnce, bundle);
2935
+ }
2936
+ function readMountedSceneShell(projectDir, entryFile, entryHtml) {
2937
+ if (!isTemplateEntry(entryHtml))
2938
+ return null;
2939
+ const indexHtml = safeReadFile(resolve2(projectDir, "index.html"));
2940
+ return indexHtml === null ? null : extractStandaloneEntryFromIndex(indexHtml, entryFile, entryHtml);
2941
+ }
2942
+ async function bundleProject(projectDir, options) {
2943
+ const entryFile = options?.entryFile ?? "index.html";
2944
+ const indexPath = resolveWithinProject(projectDir, entryFile);
2945
+ if (!indexPath || !existsSync(indexPath)) {
2946
+ throw new Error(`${entryFile} not found in project directory`);
2947
+ }
2948
+ noteRead(indexPath);
2949
+ const entryHtml = readFileSync(indexPath, "utf-8");
2950
+ const mountedShell = readMountedSceneShell(projectDir, entryFile, entryHtml);
2951
+ const sourceDir = mountedShell ? projectDir : dirname(indexPath);
2952
+ const safePaths = /* @__PURE__ */ new Map();
2953
+ const isSafeProjectPath = (resolved) => {
2954
+ let safe = safePaths.get(resolved);
2955
+ if (safe === void 0) {
2956
+ safe = isSafePath(projectDir, resolved);
2957
+ safePaths.set(resolved, safe);
2958
+ }
2959
+ return safe;
2960
+ };
2961
+ const entryPaths = /* @__PURE__ */ new Map();
2962
+ const resolveEntryPath = (relativePath) => {
2963
+ let entry = entryPaths.get(relativePath);
2964
+ if (entry === void 0) {
2965
+ const resolved = resolve2(sourceDir, relativePath);
2966
+ entry = isSafeProjectPath(resolved) ? resolved : null;
2967
+ entryPaths.set(relativePath, entry);
2968
+ }
2969
+ return entry;
2970
+ };
2971
+ const resolveProjectPath = (relativePath) => {
2972
+ const resolved = resolve2(projectDir, relativePath);
2973
+ return isSafeProjectPath(resolved) ? resolved : null;
2974
+ };
2975
+ const resolveEntryUrl = (url) => resolveEntryPath(decodedUrlPath(url));
2976
+ const readSource = options?.stampHfIds ? ensureHfIds : (html) => html;
2977
+ const rawHtml = readSource(mountedShell ?? entryHtml);
2978
+ const compiled = await compileHtml(rawHtml, sourceDir, options?.probeMediaDuration);
2979
+ if (options?.staticGuard !== false && !mountedShell) {
2980
+ const staticGuard = await validateHyperframeHtmlContract(compiled);
2981
+ if (!staticGuard.isValid) {
2982
+ console.warn(`[StaticGuard] Invalid HyperFrame contract: ${staticGuard.missingKeys.join("; ")}`);
2983
+ }
2984
+ }
2985
+ const withInterceptor = injectInterceptor(compiled, options?.runtime ?? "inline");
2986
+ const document = parseHTMLContent(withInterceptor);
2987
+ if (resolve2(sourceDir) !== resolve2(projectDir)) {
2988
+ rebaseEntryAuthoredAssetPaths(document, sourceDir, projectDir);
2989
+ }
2990
+ for (const el of [...document.querySelectorAll('link[rel="stylesheet"]')]) {
2991
+ const href = el.getAttribute("href");
2992
+ if (!href || !isRelativeUrl(href) || cssStyleMergeKey(el) === void 0)
2993
+ continue;
2994
+ if (el.hasAttribute("disabled"))
2995
+ continue;
2996
+ const cssPath = resolveEntryUrl(href);
2997
+ if (!cssPath)
2998
+ continue;
2999
+ const css = safeReadFile(cssPath);
3000
+ if (css == null)
3001
+ continue;
3002
+ const style = document.createElement("style");
3003
+ for (const name of ["media", "title"]) {
3004
+ const value = el.getAttribute(name);
3005
+ if (value !== null)
3006
+ style.setAttribute(name, value);
3007
+ }
3008
+ style.textContent = inlineCssFile(css, dirname(cssPath), projectDir, /* @__PURE__ */ new Set([cssPath]));
3009
+ el.replaceWith(style);
3010
+ }
3011
+ const rootScripts = options?.sceneParts ? [
3012
+ ...document.querySelectorAll(`script:not([${RUNTIME_BOOTSTRAP_ATTR}])`),
3013
+ ...[...document.querySelectorAll("template")].flatMap((t) => [
3014
+ ...t.content.querySelectorAll("script")
3015
+ ])
3016
+ ].map((el) => {
3017
+ const src = el.getAttribute("src");
3018
+ const path = src && isRelativeUrl(src) ? resolveEntryUrl(src) : null;
3019
+ return src ? path && safeReadFile(path) || "" : el.textContent || "";
3020
+ }) : [];
3021
+ const trackedCompositionHosts = getBundledTrackedCompositionHosts(document);
3022
+ const hostIdentityByElement = assignBundledRuntimeCompositionIds(trackedCompositionHosts);
3023
+ const subCompositionHosts = trackedCompositionHosts.filter((host) => host.hasAttribute("data-composition-src"));
3024
+ const sceneSources = /* @__PURE__ */ new Map();
3025
+ const subCompResult = inlineSubCompositions(document, subCompositionHosts, {
3026
+ resolveHtml: (srcPath) => {
3027
+ if (!isRelativeUrl(srcPath))
3028
+ return null;
3029
+ const compPath = resolveEntryPath(srcPath);
3030
+ if (!compPath)
3031
+ return null;
3032
+ let source = sceneSources.get(compPath);
3033
+ if (source === void 0) {
3034
+ const html = safeReadFile(compPath);
3035
+ source = html === null ? null : readSource(html);
3036
+ sceneSources.set(compPath, source);
3037
+ } else {
3038
+ noteRead(compPath);
3039
+ }
3040
+ return source;
3041
+ },
3042
+ parseHtml: parseHTMLContent,
3043
+ hostIdentityMap: hostIdentityByElement,
3044
+ rewriteInlineStyles: true,
3045
+ // A sub-composition's SIBLING assets (a stylesheet next to it) must be
3046
+ // re-pointed at its own directory when its content moves to the root
3047
+ // document; project-root refs with no such sibling stay as authored.
3048
+ assetExists: (path) => {
3049
+ const resolved = resolveEntryPath(path);
3050
+ if (resolved)
3051
+ noteRead(resolved);
3052
+ return resolved !== null && existsSync(resolved);
3053
+ },
3054
+ flattenInnerRoot: prepareFlattenedInnerRoot,
3055
+ tagScenes: options?.sceneParts === true,
3056
+ readVariableDefaults: readDeclaredDefaults,
3057
+ parseHostVariables: parseHostVariableValues,
3058
+ buildScopeSelector: (compId) => cssAttributeSelector("data-composition-id", compId),
3059
+ scriptErrorLabel: "[Framey] composition script error:",
3060
+ onMissingComposition: (srcPath, reason) => {
3061
+ console.warn(`[Bundler] Skipping sub-composition "${srcPath}": ${reason ?? "the file could not be found"}.`);
3062
+ }
3063
+ });
3064
+ refuseSwapsReachedByRootScripts(document, rootScripts);
3065
+ const styleRuns = [];
3066
+ subCompResult.styles.forEach((style, i) => pushRun(styleRuns, subCompResult.styleScenes[i], style));
3067
+ const scriptRuns = [];
3068
+ const compStyleChunks = [];
3069
+ const compScriptChunks = [];
3070
+ const compExternalLinks = [...subCompResult.externalLinks];
3071
+ const compVariablesByComp = {
3072
+ ...subCompResult.variablesByComp
3073
+ };
3074
+ const seenCompScriptSrcs = /* @__PURE__ */ new Set();
3075
+ for (const scriptItem of subCompResult.scriptItems) {
3076
+ if (scriptItem.kind === "inline") {
3077
+ pushRun(scriptRuns, scriptItem.scene, scriptItem.content);
3078
+ continue;
3079
+ }
3080
+ const extSrc = scriptItem.src;
3081
+ if (scriptItem.integrity?.trim()) {
3082
+ ensureExternalScriptTag(document, extSrc, scriptItem);
3083
+ seenCompScriptSrcs.add(extSrc);
3084
+ continue;
3085
+ }
3086
+ if (seenCompScriptSrcs.has(extSrc))
3087
+ continue;
3088
+ seenCompScriptSrcs.add(extSrc);
3089
+ if (isRelativeUrl(extSrc) && scriptItem.type !== "module") {
3090
+ const jsPath = resolveEntryUrl(extSrc);
3091
+ const js = jsPath ? safeReadFile(jsPath) : null;
3092
+ if (js != null) {
3093
+ const chunk = () => preserveLocalScriptIntegrity(document, extSrc, resolveEntryUrl) ? "" : js;
3094
+ pushRun(scriptRuns, scriptItem.scene, chunk);
3095
+ continue;
3096
+ }
3097
+ }
3098
+ ensureExternalScriptTag(document, extSrc, scriptItem);
3099
+ }
3100
+ const candidateInlineHosts = trackedCompositionHosts.filter((host) => !host.hasAttribute("data-composition-src"));
3101
+ for (const templateEl of [...document.querySelectorAll("template[id]")]) {
3102
+ const templateId = templateEl.getAttribute("id") || "";
3103
+ const match = templateId.match(/^(.+)-template$/);
3104
+ if (!match)
3105
+ continue;
3106
+ const compId = match[1];
3107
+ if (!compId)
3108
+ continue;
3109
+ const hosts = candidateInlineHosts.filter((host) => hostIdentityByElement.get(host)?.authoredCompositionId === compId && host.children.length === 0);
3110
+ if (hosts.length === 0)
3111
+ continue;
3112
+ const templateHtml = templateEl.innerHTML || "";
3113
+ for (const host of hosts) {
3114
+ const hostIdentity = hostIdentityByElement.get(host);
3115
+ const runtimeCompId = hostIdentity?.runtimeCompositionId || compId;
3116
+ const innerDoc = parseHTMLContent(templateHtml);
3117
+ const plan = planCompositionAssembly({
3118
+ contentNode: innerDoc,
3119
+ hasTemplate: true,
3120
+ compositionId: compId
3121
+ });
3122
+ const { innerRoot, authoredRootId } = plan;
3123
+ const runtimeScope = runtimeCompId ? cssAttributeSelector("data-composition-id", runtimeCompId) : "";
3124
+ const mergedVariables = runtimeCompId ? parseHostVariableValues(host) : {};
3125
+ if (runtimeCompId && Object.keys(mergedVariables).length > 0) {
3126
+ compVariablesByComp[runtimeCompId] = mergedVariables;
3127
+ }
3128
+ if (runtimeCompId) {
3129
+ warnUnknownEnumValues(innerDoc.documentElement, mergedVariables, runtimeCompId);
3130
+ warnUnknownEnumValues(innerRoot, mergedVariables, runtimeCompId);
3131
+ }
3132
+ pushSubCompVariableStyles(innerDoc, innerRoot, mergedVariables, runtimeScope, compStyleChunks);
3133
+ if (innerRoot) {
3134
+ for (const styleEl of [...innerRoot.querySelectorAll("style")]) {
3135
+ if (cssStyleMergeKey(styleEl) === void 0)
3136
+ continue;
3137
+ const css = styleEl.textContent || "";
3138
+ compStyleChunks.push(compositionStyle(styleEl, compId ? scopeCssToComposition(css, compId, runtimeScope, authoredRootId, {
3139
+ scopeRootSelectors: true
3140
+ }) : css));
3141
+ styleEl.remove();
3142
+ }
3143
+ hoistCompositionScripts(innerRoot, {
3144
+ projectDir,
3145
+ document,
3146
+ compId,
3147
+ runtimeScope,
3148
+ runtimeCompId,
3149
+ authoredRootId: authoredRootId ?? void 0,
3150
+ seenCompScriptSrcs,
3151
+ compScriptChunks,
3152
+ importMaps: subCompResult.importMaps,
3153
+ moduleScripts: subCompResult.moduleScripts
3154
+ });
3155
+ const innerW = innerRoot.getAttribute("data-width");
3156
+ const innerH = innerRoot.getAttribute("data-height");
3157
+ if (innerW && !host.getAttribute("data-width"))
3158
+ host.setAttribute("data-width", innerW);
3159
+ if (innerH && !host.getAttribute("data-height"))
3160
+ host.setAttribute("data-height", innerH);
3161
+ const preparedInnerRoot = prepareFlattenedInnerRoot(innerRoot);
3162
+ host.innerHTML = preparedInnerRoot.outerHTML || "";
3163
+ } else {
3164
+ for (const styleEl of [...innerDoc.querySelectorAll("style")]) {
3165
+ if (cssStyleMergeKey(styleEl) === void 0)
3166
+ continue;
3167
+ const css = styleEl.textContent || "";
3168
+ compStyleChunks.push(compositionStyle(styleEl, compId ? scopeCssToComposition(css, compId, runtimeScope, void 0, {
3169
+ scopeRootSelectors: true
3170
+ }) : css));
3171
+ styleEl.remove();
3172
+ }
3173
+ hoistCompositionScripts(innerDoc, {
3174
+ projectDir,
3175
+ document,
3176
+ compId,
3177
+ runtimeScope,
3178
+ runtimeCompId,
3179
+ authoredRootId: void 0,
3180
+ seenCompScriptSrcs,
3181
+ compScriptChunks,
3182
+ importMaps: subCompResult.importMaps,
3183
+ moduleScripts: subCompResult.moduleScripts
3184
+ });
3185
+ host.innerHTML = innerDoc.body.innerHTML || "";
3186
+ }
3187
+ for (const el of plan.inertScriptsOutsideRoot)
3188
+ host.insertAdjacentHTML("beforeend", el.outerHTML);
3189
+ }
3190
+ templateEl.remove();
3191
+ }
3192
+ for (const el of [...document.querySelectorAll("script[src]")]) {
3193
+ const src = el.getAttribute("src");
3194
+ if (!src || !isRelativeUrl(src))
3195
+ continue;
3196
+ if (preserveLocalScriptIntegrity(document, src, resolveEntryUrl))
3197
+ continue;
3198
+ if ((el.getAttribute("type") || "").trim().toLowerCase() === "module")
3199
+ continue;
3200
+ const jsPath = resolveEntryUrl(src);
3201
+ const js = jsPath ? safeReadFile(jsPath) : null;
3202
+ if (js == null)
3203
+ continue;
3204
+ el.setAttribute(INLINED_FILE_ATTR, src);
3205
+ el.removeAttribute("src");
3206
+ el.textContent = js;
3207
+ }
3208
+ for (const link of compExternalLinks)
3209
+ ensureExternalLinkTag(document, link);
3210
+ for (const css of compStyleChunks)
3211
+ pushRun(styleRuns, void 0, css);
3212
+ for (const chunk of compScriptChunks)
3213
+ pushRun(scriptRuns, void 0, chunk);
3214
+ const variablesByCompScript = buildVariablesByCompScript(compVariablesByComp);
3215
+ if (variablesByCompScript) {
3216
+ if (scriptRuns[0] && !scriptRuns[0].scene)
3217
+ scriptRuns[0].chunks.unshift(variablesByCompScript);
3218
+ else
3219
+ scriptRuns.unshift({ chunks: [variablesByCompScript] });
3220
+ }
3221
+ for (const { scene, chunks } of styleRuns) {
3222
+ const join = scene ? joinCssHoistingImports : (css) => css.join("\n\n");
3223
+ for (const style of styleElementsFor(document, chunks, join)) {
3224
+ if (scene)
3225
+ style.setAttribute(SCENE_PART_ATTR, scene);
3226
+ document.head.appendChild(style);
3227
+ }
3228
+ }
3229
+ for (const { scene, chunks } of scriptRuns) {
3230
+ const texts = chunks.map((chunk) => typeof chunk === "string" ? chunk : chunk());
3231
+ const joined = joinJsChunks(texts);
3232
+ const skipsRunMerge = Boolean(scene);
3233
+ for (const text of parsesAsScript(joined) ? [joined] : texts.filter(Boolean)) {
3234
+ const script = document.createElement("script");
3235
+ if (scene)
3236
+ script.setAttribute(SCENE_PART_ATTR, scene);
3237
+ script.textContent = skipsRunMerge ? await inlineScriptSource(text, options?.scriptProvenance) : text;
3238
+ document.body.appendChild(script);
3239
+ }
3240
+ }
3241
+ emitMountedModuleScripts(document, subCompResult.importMaps, subCompResult.moduleScripts);
3242
+ emitRootCompositionVariableStyles(document, compVariablesByComp);
3243
+ enforceCompositionPixelSizing(document);
3244
+ autoHealMissingCompositionIds(document);
3245
+ await coalesceHeadStylesAndBodyScripts(document, options?.scriptProvenance);
3246
+ for (const el of document.querySelectorAll(`script[${INLINED_FILE_ATTR}]`)) {
3247
+ const js = el.textContent ?? "";
3248
+ el.textContent = escapeInlineScriptSource(isJavaScriptType(el) ? await stripJsCommentsParserSafe(js, options?.scriptProvenance) : js);
3249
+ }
3250
+ deferScriptsUntilFonts(document, (el) => el.hasAttribute(RUNTIME_BOOTSTRAP_ATTR));
3251
+ injectTextRenderingRule(document);
3252
+ const inlineAssets = options?.inlineAssets !== false;
3253
+ const inlineAsset = createAssetInliner(resolveProjectPath, inlineAssets);
3254
+ for (const el of [...document.querySelectorAll("[src], [href], [poster], [xlink\\:href]")]) {
3255
+ for (const attr of ["src", "href", "poster", "xlink:href"]) {
3256
+ const value = el.getAttribute(attr);
3257
+ if (!value)
3258
+ continue;
3259
+ if (isExternalSvgFragmentUse(el, attr, value))
3260
+ continue;
3261
+ const inlined = inlineAsset(value);
3262
+ if (inlined)
3263
+ el.setAttribute(attr, inlined);
3264
+ }
3265
+ }
3266
+ for (const el of [...document.querySelectorAll("[srcset]")]) {
3267
+ const srcset = el.getAttribute("srcset");
3268
+ if (srcset)
3269
+ el.setAttribute("srcset", rewriteSrcsetUrls(srcset, (url) => inlineAsset(url) ?? url));
3270
+ }
3271
+ const liveStyles = [...document.querySelectorAll("style")].filter(isAlwaysAppliedStyle);
3272
+ const liveCss = liveStyles.map((el) => el.textContent || "");
3273
+ const { styles, faces } = options?.sceneParts ? hoistFontFaceRules(liveCss) : { styles: dedupeFontFaceRules(liveCss), faces: [] };
3274
+ liveStyles.forEach((el, i) => {
3275
+ el.textContent = styles[i] ?? "";
3276
+ });
3277
+ if (faces.length > 0) {
3278
+ const holder = document.createElement("style");
3279
+ holder.setAttribute(SCENE_FONTS_ATTR, "");
3280
+ holder.textContent = faces.join("\n");
3281
+ document.head.prepend(holder);
3282
+ }
3283
+ for (const styleEl of document.querySelectorAll("style")) {
3284
+ styleEl.textContent = rewriteCssUrlsWithInlinedAssets(styleEl.textContent || "", inlineAsset);
3285
+ }
3286
+ for (const el of [...document.querySelectorAll("[style]")]) {
3287
+ el.setAttribute("style", rewriteCssUrlsWithInlinedAssets(el.getAttribute("style") || "", inlineAsset));
3288
+ }
3289
+ if (inlineAssets && options?.inlineColorGradingLuts !== false) {
3290
+ for (const el of [...document.querySelectorAll(`[${HF_COLOR_GRADING_ATTR}]`)]) {
3291
+ const value = el.getAttribute(HF_COLOR_GRADING_ATTR);
3292
+ if (value) {
3293
+ el.setAttribute(HF_COLOR_GRADING_ATTR, rewriteColorGradingLutWithInlinedAssets(value, inlineAsset));
3294
+ }
3295
+ }
3296
+ }
3297
+ assignMediaRenderIds(document);
3298
+ return document.toString();
3299
+ }
3300
+ function cssSafeVariableValue(value) {
3301
+ return sanitizeCssValue(String(value)).replace(/</g, "\\3c ");
3302
+ }
3303
+ function compositionVariablesCssBlock(variables, selector) {
3304
+ const lines = [];
3305
+ for (const [id, value] of Object.entries(variables)) {
3306
+ if (typeof value === "string" && value !== "" || typeof value === "number") {
3307
+ lines.push(` ${cssVariableName(id)}: ${cssSafeVariableValue(value)};`);
3308
+ }
3309
+ }
3310
+ if (lines.length === 0)
3311
+ return null;
3312
+ return `${selector} {
3313
+ ${lines.join("\n")}
3314
+ }`;
3315
+ }
3316
+ function emitRootCompositionVariableStyles(document, variablesByComp = {}, overrides = {}) {
3317
+ const authoredDefines = authoredDefinesPredicate(document);
3318
+ const layerFor = makeVariableLayer(authoredDefines, overrides);
3319
+ const rules = [
3320
+ ...hostScopedVariableRules(variablesByComp, overrides, authoredDefines),
3321
+ ...rootDeclaredVariableRules(document, layerFor),
3322
+ ...declarerVariableRules(document, layerFor)
3323
+ ];
3324
+ if (rules.length === 0)
3325
+ return false;
3326
+ const style = document.createElement("style");
3327
+ style.setAttribute("data-hf-composition-variables", "");
3328
+ style.textContent = rules.join("\n\n");
3329
+ document.head.appendChild(style);
3330
+ return true;
3331
+ }
3332
+ function authoredDefinesPredicate(document) {
3333
+ const authoredCss = [...document.querySelectorAll("style:not([data-hf-composition-variables])")].map((s) => s.textContent || "").join("\n");
3334
+ const defined = namesBeforeAColon(authoredCss);
3335
+ return (id) => defined.has(cssVariableName(id));
3336
+ }
3337
+ function namesBeforeAColon(css) {
3338
+ const names = /* @__PURE__ */ new Set();
3339
+ const word = /[\w-]+/g;
3340
+ const colonNext = /\s*:/y;
3341
+ for (let match = word.exec(css); match; match = word.exec(css)) {
3342
+ colonNext.lastIndex = word.lastIndex;
3343
+ if (!colonNext.test(css))
3344
+ continue;
3345
+ const text = match[0];
3346
+ for (let at = text.indexOf("--"); at !== -1; at = text.indexOf("--", at + 1))
3347
+ names.add(text.slice(at));
3348
+ }
3349
+ return names;
3350
+ }
3351
+ function makeVariableLayer(authoredDefines, overrides) {
3352
+ return (declared, hostValues) => {
3353
+ const out = {};
3354
+ for (const [id, value] of Object.entries(declared)) {
3355
+ if (!authoredDefines(id))
3356
+ out[id] = value;
3357
+ }
3358
+ for (const [id, value] of Object.entries(hostValues)) {
3359
+ if (id in declared)
3360
+ out[id] = value;
3361
+ }
3362
+ for (const [id, value] of Object.entries(overrides)) {
3363
+ if (id in declared || id in hostValues)
3364
+ out[id] = value;
3365
+ }
3366
+ return out;
3367
+ };
3368
+ }
3369
+ function hostScopedVariableRules(variablesByComp, overrides, authoredDefines) {
3370
+ const rules = [];
3371
+ for (const [compId, vars] of Object.entries(variablesByComp)) {
3372
+ const withOverrides = {};
3373
+ for (const [id, value] of Object.entries(vars)) {
3374
+ if (!authoredDefines(id))
3375
+ withOverrides[id] = value;
3376
+ }
3377
+ for (const [id, value] of Object.entries(overrides)) {
3378
+ if (id in vars)
3379
+ withOverrides[id] = value;
3380
+ }
3381
+ const rule = compositionVariablesCssBlock(withOverrides, cssAttributeSelector("data-composition-id", compId));
3382
+ if (rule)
3383
+ rules.push(rule);
3384
+ }
3385
+ return rules;
3386
+ }
3387
+ function rootDeclaredVariableRules(document, layerFor) {
3388
+ const htmlDeclared = readDeclaredDefaults(document.documentElement);
3389
+ const htmlRule = compositionVariablesCssBlock(layerFor(htmlDeclared, {}), ":root");
3390
+ return htmlRule ? [htmlRule] : [];
3391
+ }
3392
+ function declarerVariableRules(document, layerFor) {
3393
+ const rules = [];
3394
+ let markerSeq = 0;
3395
+ for (const el of [...document.querySelectorAll("[data-composition-variables]")]) {
3396
+ const declared = readDeclaredDefaults(el);
3397
+ const hostEl = typeof el.closest === "function" ? el.parentElement?.closest("[data-variable-values]") : null;
3398
+ const hostValues = hostEl ? parseHostVariableValues(hostEl) : {};
3399
+ const vars = layerFor(declared, hostValues);
3400
+ if (Object.keys(vars).length === 0)
3401
+ continue;
3402
+ markerSeq += 1;
3403
+ el.setAttribute("data-hf-var-scope", String(markerSeq));
3404
+ const rule = compositionVariablesCssBlock(vars, `[data-hf-var-scope="${markerSeq}"]`);
3405
+ if (rule)
3406
+ rules.push(rule);
3407
+ }
3408
+ return rules;
3409
+ }
3410
+ function pushSubCompVariableStyles(innerDoc, innerRoot, mergedVariables, runtimeScope, compStyleChunks) {
3411
+ if (!runtimeScope)
3412
+ return;
3413
+ const declaredForCss = readDeclaredDefaults(innerDoc.documentElement);
3414
+ const innerRootForVars = innerRoot ?? innerDoc.querySelector("[data-composition-variables]");
3415
+ if (innerRootForVars)
3416
+ Object.assign(declaredForCss, readDeclaredDefaults(innerRootForVars));
3417
+ const cssVars = compositionVariablesCssBlock({ ...declaredForCss, ...mergedVariables }, runtimeScope);
3418
+ if (cssVars)
3419
+ compStyleChunks.push({ css: cssVars, media: null, title: null });
3420
+ }
3421
+
3422
+ // ../core/dist/compiler/htmlParityContract.js
3423
+ function finiteAttribute(element, name) {
3424
+ const raw = element.getAttribute(name);
3425
+ if (raw === null || raw.trim() === "")
3426
+ return null;
3427
+ const value = Number(raw);
3428
+ return Number.isFinite(value) ? value : null;
3429
+ }
3430
+ function timing(element) {
3431
+ const start = finiteAttribute(element, "data-start") ?? 0;
3432
+ const duration = finiteAttribute(element, "data-duration") ?? (() => {
3433
+ const end = finiteAttribute(element, "data-end");
3434
+ return end === null ? null : Math.max(0, end - start);
3435
+ })();
3436
+ return {
3437
+ start,
3438
+ duration,
3439
+ trackIndex: finiteAttribute(element, "data-track-index") ?? finiteAttribute(element, "data-layer")
3440
+ };
3441
+ }
3442
+ function normalizeJson(value) {
3443
+ if (value === null)
3444
+ return null;
3445
+ try {
3446
+ return JSON.stringify(canonicalizeJson(JSON.parse(value)));
3447
+ } catch {
3448
+ return value.trim();
3449
+ }
3450
+ }
3451
+ function canonicalizeJson(value) {
3452
+ if (Array.isArray(value))
3453
+ return value.map(canonicalizeJson);
3454
+ if (value === null || typeof value !== "object")
3455
+ return value;
3456
+ return Object.fromEntries(Object.entries(value).sort(([left], [right]) => left.localeCompare(right)).map(([key, nested]) => [key, canonicalizeJson(nested)]));
3457
+ }
3458
+ function styleSignatures(document) {
3459
+ return [...document.querySelectorAll("style")].map((style) => style.textContent ?? "").flatMap((css) => css.match(/[^{}]+\{[^{}]*--parity-contract\s*:[^{}]+\}/g) ?? []).map((rule) => rule.replace(/\s+/g, " ").replace(/\s*([:;{},])\s*/g, "$1").trim()).sort();
3460
+ }
3461
+ function parityFontFamilies(html) {
3462
+ const families = /* @__PURE__ */ new Set();
3463
+ for (const match of html.matchAll(/font-family\s*:\s*([^;}]+)/gi)) {
3464
+ for (const family of match[1].split(",")) {
3465
+ const normalized = family.trim().replace(/^['"]|['"]$/g, "");
3466
+ if (normalized.startsWith("Parity"))
3467
+ families.add(normalized);
3468
+ }
3469
+ }
3470
+ return [...families].sort();
3471
+ }
3472
+ function resources(document) {
3473
+ const resources2 = [];
3474
+ for (const [index, element] of [
3475
+ ...document.querySelectorAll("[src], [href], [poster]")
3476
+ ].entries()) {
3477
+ for (const attribute of ["src", "href", "poster"]) {
3478
+ const value = element.getAttribute(attribute)?.trim();
3479
+ if (!value)
3480
+ continue;
3481
+ if (element.tagName.toLowerCase() === "script" && /framey|runtime/i.test(value))
3482
+ continue;
3483
+ resources2.push({
3484
+ identity: element.getAttribute("data-hf-id") ?? element.getAttribute("id") ?? `${element.tagName.toLowerCase()}[${index}]`,
3485
+ attribute,
3486
+ locality: /^https?:\/\//i.test(value) ? "remote" : "local"
3487
+ });
3488
+ }
3489
+ }
3490
+ return resources2.sort((left, right) => `${left.identity}:${left.attribute}`.localeCompare(`${right.identity}:${right.attribute}`));
3491
+ }
3492
+ function extractCompiledHtmlParityContract(html) {
3493
+ const { document } = parseHTML(html);
3494
+ const compositions = [...document.querySelectorAll("[data-composition-id]")].map((element) => {
3495
+ const resolved = timing(element);
3496
+ return {
3497
+ id: element.getAttribute("data-composition-id") ?? "",
3498
+ originalId: element.getAttribute("data-hf-original-composition-id"),
3499
+ ...resolved,
3500
+ width: finiteAttribute(element, "data-width"),
3501
+ height: finiteAttribute(element, "data-height"),
3502
+ variableValues: normalizeJson(element.getAttribute("data-variable-values"))
3503
+ };
3504
+ });
3505
+ const timedElements = [
3506
+ ...document.querySelectorAll("[data-start], [data-duration], [data-end], [data-track-index], [data-layer]")
3507
+ ].filter((element) => !element.hasAttribute("data-composition-id")).map((element, index) => ({
3508
+ identity: element.getAttribute("data-hf-id") ?? element.getAttribute("id") ?? `${element.tagName.toLowerCase()}[${index}]`,
3509
+ ...timing(element)
3510
+ }));
3511
+ return {
3512
+ compositions,
3513
+ timedElements,
3514
+ authoredStyleSignatures: styleSignatures(document),
3515
+ parityFontFamilies: parityFontFamilies(html),
3516
+ resources: resources(document),
3517
+ runtimeBootstrap: /__hyperframes|data-hyperframes-(?:preview-)?runtime/i.test(html),
3518
+ variableBootstrap: /__hfVariables(?:ByComp)?/.test(html)
3519
+ };
3520
+ }
3521
+
3522
+ // ../core/dist/compiler/scenePartsManifest.js
3523
+ import { createHash as createHash2 } from "crypto";
3524
+ var hash = (text) => createHash2("sha1").update(text).digest("hex").slice(0, 16);
3525
+ function addScenePartsManifest(html, ignore = []) {
3526
+ const doc = parseHTMLContent(html);
3527
+ const parts = [...doc.querySelectorAll(`[${SCENE_PART_ATTR}]`)];
3528
+ if (parts.length === 0)
3529
+ return html;
3530
+ const byScene = /* @__PURE__ */ new Map();
3531
+ for (const el of parts) {
3532
+ const scene = el.getAttribute(SCENE_PART_ATTR) ?? "";
3533
+ byScene.set(scene, [...byScene.get(scene) ?? [], el.outerHTML]);
3534
+ }
3535
+ for (const el of parts)
3536
+ el.replaceWith(doc.createComment(`hf-scene:${el.getAttribute(SCENE_PART_ATTR)}`));
3537
+ for (const el of [...ignore, `style[${SCENE_FONTS_ATTR}]`].flatMap((sel) => [
3538
+ ...doc.querySelectorAll(sel)
3539
+ ]))
3540
+ el.remove();
3541
+ const manifest = {
3542
+ shared: hash(doc.toString()),
3543
+ scenes: Object.fromEntries([...byScene].map(([scene, html2]) => [scene, hash(html2.join("\n"))]))
3544
+ };
3545
+ const content = JSON.stringify(manifest).replace(/&/g, "&amp;").replace(/"/g, "&quot;");
3546
+ return injectTagsAtHeadStart(html, `<meta name="${SCENE_PARTS_META}" content="${content}">`);
3547
+ }
3548
+
3549
+ export {
3550
+ compileHtml,
3551
+ ensureExternalScriptTag,
3552
+ emitMountedModuleScripts,
3553
+ FLATTENED_INNER_ROOT_STRIP_ATTRS,
3554
+ extractStandaloneEntryFromIndex,
3555
+ scopeCssToComposition,
3556
+ wrapScopedCompositionScript,
3557
+ buildVariablesByCompScript,
3558
+ validateHyperframeHtmlContract,
3559
+ ensureExternalLinkTag,
3560
+ inlineSubCompositions,
3561
+ EXCLUDED_TAGS,
3562
+ mintHfId,
3563
+ walkCompositionDescendants,
3564
+ ensureHfIds,
3565
+ stampHfIdsInPlace,
3566
+ assignBundledRuntimeCompositionIds,
3567
+ prepareFlattenedInnerRoot,
3568
+ parsesAsScript,
3569
+ bundleToSingleHtml,
3570
+ emitRootCompositionVariableStyles,
3571
+ extractCompiledHtmlParityContract,
3572
+ addScenePartsManifest
3573
+ };