@agent-native/core 0.103.1 → 0.104.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 (565) hide show
  1. package/corpus/README.md +2 -2
  2. package/corpus/core/CHANGELOG.md +30 -0
  3. package/corpus/core/package.json +9 -2
  4. package/corpus/core/src/agent/engine/credential-errors.ts +2 -2
  5. package/corpus/core/src/agent/production-agent.ts +30 -0
  6. package/corpus/core/src/agent/run-store.ts +12 -2
  7. package/corpus/core/src/cli/create.ts +1 -0
  8. package/corpus/core/src/cli/skills-content/visual-plan-skill.ts +30 -11
  9. package/corpus/core/src/cli/templates-meta.ts +4 -3
  10. package/corpus/core/src/client/AgentAskPopover.tsx +89 -0
  11. package/corpus/core/src/client/AgentChatHome.tsx +4 -0
  12. package/corpus/core/src/client/AgentPanel.tsx +321 -223
  13. package/corpus/core/src/client/AssistantChat.tsx +6 -10
  14. package/corpus/core/src/client/MultiTabAssistantChat.tsx +53 -372
  15. package/corpus/core/src/client/agent-chat-adapter.ts +13 -1
  16. package/corpus/core/src/client/agent-page/AgentContextTab.tsx +133 -149
  17. package/corpus/core/src/client/agent-page/AgentEmptyState.tsx +44 -0
  18. package/corpus/core/src/client/agent-page/AgentJobsTab.tsx +153 -82
  19. package/corpus/core/src/client/agent-page/AgentTabFrame.tsx +39 -0
  20. package/corpus/core/src/client/agent-page/AgentTabsPage.tsx +368 -356
  21. package/corpus/core/src/client/agent-page/types.ts +1 -1
  22. package/corpus/core/src/client/analytics.ts +51 -5
  23. package/corpus/core/src/client/chat/run-recovery.tsx +12 -4
  24. package/corpus/core/src/client/composer/PromptComposer.tsx +5 -15
  25. package/corpus/core/src/client/composer/TiptapComposer.tsx +32 -3
  26. package/corpus/core/src/client/dynamic-suggestions.ts +3 -3
  27. package/corpus/core/src/client/index.ts +16 -1
  28. package/corpus/core/src/client/resources/ResourceTree.tsx +249 -38
  29. package/corpus/core/src/client/resources/ResourcesPanel.tsx +307 -140
  30. package/corpus/core/src/client/session-replay.ts +158 -5
  31. package/corpus/core/src/client/settings/AutomationsSection.tsx +30 -10
  32. package/corpus/core/src/client/settings/SettingsPanel.tsx +3 -2
  33. package/corpus/core/src/client/settings/SettingsTabsPage.tsx +2 -0
  34. package/corpus/core/src/client/settings/agent-settings-search.ts +2 -2
  35. package/corpus/core/src/client/use-chat-threads.ts +2 -0
  36. package/corpus/core/src/connections/catalog.ts +49 -7
  37. package/corpus/core/src/db/index.ts +6 -1
  38. package/corpus/core/src/extensions/actions.ts +106 -16
  39. package/corpus/core/src/extensions/content-patch.ts +22 -0
  40. package/corpus/core/src/extensions/routes.ts +18 -0
  41. package/corpus/core/src/extensions/store.ts +8 -0
  42. package/corpus/core/src/index.ts +3 -0
  43. package/corpus/core/src/ingestion/docx.ts +158 -0
  44. package/corpus/core/src/ingestion/figma-node-to-html.ts +1860 -0
  45. package/corpus/core/src/ingestion/figma.ts +548 -0
  46. package/corpus/core/src/ingestion/index.ts +107 -0
  47. package/corpus/core/src/ingestion/media.ts +264 -0
  48. package/corpus/core/src/ingestion/notion.ts +121 -0
  49. package/corpus/core/src/ingestion/office.ts +214 -0
  50. package/corpus/core/src/ingestion/orchestration.ts +160 -0
  51. package/corpus/core/src/ingestion/pptx.ts +333 -0
  52. package/corpus/core/src/ingestion/selection.ts +81 -0
  53. package/corpus/core/src/ingestion/website.ts +151 -0
  54. package/corpus/core/src/integrations/plugin.ts +45 -37
  55. package/corpus/core/src/localization/default-messages.ts +35 -12
  56. package/corpus/core/src/observability/hosted-model-experiment.ts +118 -0
  57. package/corpus/core/src/observability/traces.ts +5 -3
  58. package/corpus/core/src/provider-api/index.ts +452 -8
  59. package/corpus/core/src/scripts/agent-engines/list-agent-engines.ts +18 -1
  60. package/corpus/core/src/search-utils/index.ts +112 -0
  61. package/corpus/core/src/secrets/register-framework-secrets.ts +61 -0
  62. package/corpus/core/src/server/action-discovery.ts +33 -8
  63. package/corpus/core/src/server/agent-chat/framework-prompts.ts +2 -2
  64. package/corpus/core/src/server/agent-chat/prompt-resources.ts +144 -0
  65. package/corpus/core/src/server/agent-chat-plugin.ts +6 -0
  66. package/corpus/core/src/server/core-routes-plugin.ts +12 -0
  67. package/corpus/core/src/server/index.ts +30 -0
  68. package/corpus/core/src/server/workspace-provider-oauth.ts +583 -0
  69. package/corpus/core/src/styles/agent-native.css +9 -0
  70. package/corpus/core/src/templates/default/app/i18n/en-US.ts +3 -3
  71. package/corpus/core/src/templates/workspace-core/.agents/skills/extensions/SKILL.md +14 -5
  72. package/corpus/core/src/templates/workspace-root/.env.example +12 -0
  73. package/corpus/core/src/workspace-connections/index.ts +6 -0
  74. package/corpus/core/src/workspace-connections/lifecycle.ts +43 -0
  75. package/corpus/core/src/workspace-connections/store.ts +16 -0
  76. package/corpus/templates/analytics/.agents/skills/dashboard-management/SKILL.md +46 -3
  77. package/corpus/templates/analytics/AGENTS.md +9 -0
  78. package/corpus/templates/analytics/actions/dashboard-mutation-api.ts +120 -6
  79. package/corpus/templates/analytics/actions/mutate-dashboard.ts +92 -30
  80. package/corpus/templates/analytics/actions/update-dashboard.ts +5 -5
  81. package/corpus/templates/analytics/app/components/dashboard/SqlChart.tsx +313 -220
  82. package/corpus/templates/analytics/app/components/layout/CommandPalette.tsx +2 -2
  83. package/corpus/templates/analytics/app/components/layout/Layout.tsx +9 -6
  84. package/corpus/templates/analytics/app/components/layout/Sidebar.tsx +90 -64
  85. package/corpus/templates/analytics/app/i18n-data.ts +3 -3
  86. package/corpus/templates/analytics/app/lib/dashboard-list-loading.ts +25 -0
  87. package/corpus/templates/analytics/app/lib/item-popularity.ts +13 -4
  88. package/corpus/templates/analytics/app/pages/adhoc/sql-dashboard/DashboardFilterBar.tsx +1 -1
  89. package/corpus/templates/analytics/app/pages/adhoc/sql-dashboard/pivot.ts +8 -3
  90. package/corpus/templates/analytics/app/pages/adhoc/sql-dashboard/types.ts +1 -0
  91. package/corpus/templates/analytics/app/pages/sessions/SessionDetailPage.tsx +15 -3
  92. package/corpus/templates/analytics/changelog/2026-07-16-dashboard-filter-defaults-can-now-be-changed-reliably-withou.md +6 -0
  93. package/corpus/templates/analytics/changelog/2026-07-16-dashboard-lists-load-in-one-stable-order-without-popping-bet.md +6 -0
  94. package/corpus/templates/analytics/changelog/2026-07-16-fixed-dashboard-filter-dropdown-text-alignment.md +6 -0
  95. package/corpus/templates/analytics/changelog/2026-07-16-recurring-signed-in-users-can-now-be-viewed-as-weekly-bars-b.md +6 -0
  96. package/corpus/templates/analytics/changelog/2026-07-16-the-analytics-agent-can-now-duplicate-a-chart-and-place-the-.md +6 -0
  97. package/corpus/templates/analytics/seeds/dashboards/agent-native-templates-first-party.json +41 -1
  98. package/corpus/templates/analytics/server/lib/dashboard-catalog.ts +1 -1
  99. package/corpus/templates/analytics/server/lib/first-party-metric-catalog.ts +47 -1
  100. package/corpus/templates/analytics/server/lib/session-replay.ts +68 -0
  101. package/corpus/templates/analytics/server/plugins/agent-chat.ts +1 -0
  102. package/corpus/templates/analytics/server/routes/sessions/lookup.get.ts +47 -0
  103. package/corpus/templates/assets/.agents/skills/asset-generation/SKILL.md +16 -9
  104. package/corpus/templates/assets/.agents/skills/creative-context/SKILL.md +86 -0
  105. package/corpus/templates/assets/AGENTS.md +10 -0
  106. package/corpus/templates/assets/actions/create-generation-session.ts +59 -1
  107. package/corpus/templates/assets/actions/edit-image.ts +2 -0
  108. package/corpus/templates/assets/actions/generate-asset.ts +52 -0
  109. package/corpus/templates/assets/actions/generate-image-batch.ts +55 -0
  110. package/corpus/templates/assets/actions/generate-image.ts +219 -1
  111. package/corpus/templates/assets/actions/open-asset-picker.ts +14 -0
  112. package/corpus/templates/assets/actions/refine-image.ts +3 -0
  113. package/corpus/templates/assets/actions/restyle-image.ts +2 -0
  114. package/corpus/templates/assets/agent-native.app-skill.json +4 -0
  115. package/corpus/templates/assets/app/components/layout/Layout.tsx +2 -0
  116. package/corpus/templates/assets/app/i18n/zh-TW.ts +3 -0
  117. package/corpus/templates/assets/app/i18n-data.ts +29 -13
  118. package/corpus/templates/assets/app/routes/agent.tsx +7 -1
  119. package/corpus/templates/assets/app/routes/library.tsx +9 -0
  120. package/corpus/templates/assets/app/routes/settings.tsx +3 -0
  121. package/corpus/templates/assets/changelog/2026-07-16-creative-context-library.md +6 -0
  122. package/corpus/templates/assets/package.json +1 -0
  123. package/corpus/templates/assets/server/lib/image-processing.ts +1 -22
  124. package/corpus/templates/assets/server/plugins/creative-context.ts +205 -0
  125. package/corpus/templates/brain/app/i18n-data.ts +3 -3
  126. package/corpus/templates/brain/app/lib/brain.ts +1 -1
  127. package/corpus/templates/brain/server/lib/search.ts +17 -67
  128. package/corpus/templates/calendar/app/i18n-data.ts +3 -3
  129. package/corpus/templates/calendar/app/pages/BookingLinksPage.tsx +19 -18
  130. package/corpus/templates/chat/app/i18n/en-US.ts +3 -3
  131. package/corpus/templates/chat/app/lib/agent-page.tsx +10 -1
  132. package/corpus/templates/clips/.agents/skills/meetings/SKILL.md +1 -1
  133. package/corpus/templates/clips/AGENTS.md +4 -0
  134. package/corpus/templates/clips/actions/cleanup-transcript.ts +35 -4
  135. package/corpus/templates/clips/actions/create-meeting.ts +6 -2
  136. package/corpus/templates/clips/actions/create-organization.ts +3 -2
  137. package/corpus/templates/clips/actions/create-recording.ts +4 -1
  138. package/corpus/templates/clips/actions/finalize-recording.ts +44 -7
  139. package/corpus/templates/clips/actions/import-loom-recording.ts +4 -1
  140. package/corpus/templates/clips/actions/lib/create-recording-schema.ts +2 -2
  141. package/corpus/templates/clips/actions/list-meetings.ts +23 -5
  142. package/corpus/templates/clips/actions/list-organization-state.ts +1 -1
  143. package/corpus/templates/clips/actions/remove-silences.ts +10 -1
  144. package/corpus/templates/clips/actions/request-transcript.ts +53 -11
  145. package/corpus/templates/clips/actions/search-recordings-utils.ts +7 -0
  146. package/corpus/templates/clips/actions/search-recordings.ts +5 -8
  147. package/corpus/templates/clips/actions/set-organization-branding.ts +2 -2
  148. package/corpus/templates/clips/actions/stitch-recordings.ts +10 -5
  149. package/corpus/templates/clips/actions/update-ai-request-status.ts +38 -0
  150. package/corpus/templates/clips/app/components/editor/editor-layout.tsx +3 -4
  151. package/corpus/templates/clips/app/components/editor/editor-selection.ts +19 -0
  152. package/corpus/templates/clips/app/components/editor/stitch-manager.tsx +10 -10
  153. package/corpus/templates/clips/app/components/library/bulk-action-toolbar.tsx +1 -2
  154. package/corpus/templates/clips/app/components/library/library-grid.tsx +101 -93
  155. package/corpus/templates/clips/app/components/player/video-player.tsx +11 -0
  156. package/corpus/templates/clips/app/components/workspace/branding-editor.tsx +53 -1
  157. package/corpus/templates/clips/app/i18n/ar-SA.ts +7 -1
  158. package/corpus/templates/clips/app/i18n/de-DE.ts +7 -1
  159. package/corpus/templates/clips/app/i18n/en-US.ts +10 -4
  160. package/corpus/templates/clips/app/i18n/es-ES.ts +7 -1
  161. package/corpus/templates/clips/app/i18n/fr-FR.ts +7 -1
  162. package/corpus/templates/clips/app/i18n/hi-IN.ts +7 -1
  163. package/corpus/templates/clips/app/i18n/ja-JP.ts +7 -1
  164. package/corpus/templates/clips/app/i18n/ko-KR.ts +7 -1
  165. package/corpus/templates/clips/app/i18n/pt-BR.ts +7 -1
  166. package/corpus/templates/clips/app/i18n/zh-CN.ts +6 -1
  167. package/corpus/templates/clips/app/i18n/zh-TW.ts +6 -1
  168. package/corpus/templates/clips/app/routes/_app.settings._index.tsx +5 -9
  169. package/corpus/templates/clips/app/routes/_app.settings.organization.tsx +6 -2
  170. package/corpus/templates/clips/app/routes/r.$recordingId.tsx +129 -27
  171. package/corpus/templates/clips/app/routes/record.tsx +23 -2
  172. package/corpus/templates/clips/app/routes/share.$shareId.tsx +6 -2
  173. package/corpus/templates/clips/changelog/2026-07-16-authorized-viewers-can-open-shared-private-clips-without-a-m.md +6 -0
  174. package/corpus/templates/clips/changelog/2026-07-16-camera-bubble-hover-controls-appear-above-the-face.md +6 -0
  175. package/corpus/templates/clips/changelog/2026-07-16-chrome-extension-recovers-stale-recorder-state.md +6 -0
  176. package/corpus/templates/clips/changelog/2026-07-16-clips-agent-chat-no-longer-shows-a-separate-workspace-header.md +6 -0
  177. package/corpus/templates/clips/changelog/2026-07-16-clips-search-now-matches-recording-content-without-requiring.md +6 -0
  178. package/corpus/templates/clips/changelog/2026-07-16-declined-meetings-no-longer-show-desktop-reminders.md +6 -0
  179. package/corpus/templates/clips/changelog/2026-07-16-failed-desktop-saves-now-show-their-local-recovery-copy.md +6 -0
  180. package/corpus/templates/clips/changelog/2026-07-16-long-desktop-clips-now-preserve-complete-playback-synced-aud.md +6 -0
  181. package/corpus/templates/clips/changelog/2026-07-16-long-recording-lists-keep-stitch-and-library-actions-visible.md +6 -0
  182. package/corpus/templates/clips/changelog/2026-07-16-organization-admins-can-choose-new-recording-visibility.md +6 -0
  183. package/corpus/templates/clips/changelog/2026-07-16-remove-silences-now-shows-queued-active-completed-and-failed.md +6 -0
  184. package/corpus/templates/clips/changelog/2026-07-16-settings-no-longer-repeats-the-builder-connection-status-in-.md +6 -0
  185. package/corpus/templates/clips/changelog/2026-07-16-transcripts-now-appear-from-native-browser-speech-sooner-wit.md +6 -0
  186. package/corpus/templates/clips/chrome-extension/public/manifest.json +1 -1
  187. package/corpus/templates/clips/chrome-extension/src/background.ts +73 -1
  188. package/corpus/templates/clips/chrome-extension/src/native-recording-state.ts +32 -0
  189. package/corpus/templates/clips/chrome-extension/src/native-transcription.ts +248 -0
  190. package/corpus/templates/clips/chrome-extension/src/offscreen.ts +106 -0
  191. package/corpus/templates/clips/desktop/src/app.tsx +66 -28
  192. package/corpus/templates/clips/desktop/src/lib/recorder.ts +335 -285
  193. package/corpus/templates/clips/desktop/src/lib/single-flight.ts +7 -0
  194. package/corpus/templates/clips/desktop/src/lib/upload-verification.ts +51 -0
  195. package/corpus/templates/clips/desktop/src/overlays/bubble.tsx +2 -2
  196. package/corpus/templates/clips/desktop/src/overlays/finalizing.tsx +10 -2
  197. package/corpus/templates/clips/desktop/src/styles.css +13 -11
  198. package/corpus/templates/clips/desktop/src-tauri/src/clips/mod.rs +8 -9
  199. package/corpus/templates/clips/desktop/src-tauri/src/meetings_watcher.rs +1 -0
  200. package/corpus/templates/clips/desktop/src-tauri/src/native_screen/custom_capture.rs +88 -13
  201. package/corpus/templates/clips/desktop/src-tauri/src/native_screen/live_upload.rs +13 -2
  202. package/corpus/templates/clips/desktop/src-tauri/src/native_screen.rs +241 -6
  203. package/corpus/templates/clips/server/db/schema.ts +2 -2
  204. package/corpus/templates/clips/server/lib/builder-media-compression.ts +64 -67
  205. package/corpus/templates/clips/server/lib/calendar-event-classification.ts +19 -0
  206. package/corpus/templates/clips/server/lib/google-calendar-client.ts +1 -0
  207. package/corpus/templates/clips/server/lib/recordings.ts +40 -1
  208. package/corpus/templates/clips/server/plugins/agent-chat.ts +1 -0
  209. package/corpus/templates/clips/server/plugins/db.ts +2 -2
  210. package/corpus/templates/clips/server/routes/api/auth/google-calendar.get.ts +1 -1
  211. package/corpus/templates/clips/server/routes/api/public-recording.get.ts +14 -5
  212. package/corpus/templates/clips/server/routes/api/uploads/[recordingId]/chunk.post.ts +51 -1
  213. package/corpus/templates/clips/server/routes/api/video/[recordingId].get.ts +1 -64
  214. package/corpus/templates/clips/shared/media-worker-contract.ts +32 -15
  215. package/corpus/templates/content/.agents/skills/content/SKILL.md +16 -0
  216. package/corpus/templates/content/.agents/skills/creative-context/SKILL.md +85 -0
  217. package/corpus/templates/content/.agents/skills/notion-integration/SKILL.md +8 -0
  218. package/corpus/templates/content/AGENTS.md +9 -0
  219. package/corpus/templates/content/actions/create-document.ts +94 -0
  220. package/corpus/templates/content/actions/edit-document.ts +144 -4
  221. package/corpus/templates/content/actions/update-document.ts +138 -0
  222. package/corpus/templates/content/agent-native.app-skill.json +4 -0
  223. package/corpus/templates/content/app/components/layout/Layout.tsx +2 -0
  224. package/corpus/templates/content/app/i18n/zh-TW.ts +3 -0
  225. package/corpus/templates/content/app/i18n-data.ts +13 -4
  226. package/corpus/templates/content/app/routes/_app.agent.tsx +2 -1
  227. package/corpus/templates/content/app/routes/_app.settings.tsx +3 -0
  228. package/corpus/templates/content/changelog/2026-07-16-creative-context-library.md +6 -0
  229. package/corpus/templates/content/package.json +1 -0
  230. package/corpus/templates/content/server/plugins/creative-context.ts +31 -0
  231. package/corpus/templates/design/.agents/skills/creative-context/SKILL.md +116 -0
  232. package/corpus/templates/design/.agents/skills/design-generation/SKILL.md +16 -0
  233. package/corpus/templates/design/.agents/skills/design-systems/SKILL.md +8 -0
  234. package/corpus/templates/design/AGENTS.md +6 -0
  235. package/corpus/templates/design/actions/clone-creative-context-design.ts +176 -0
  236. package/corpus/templates/design/actions/edit-design.ts +128 -0
  237. package/corpus/templates/design/actions/generate-design.ts +278 -14
  238. package/corpus/templates/design/actions/generate-screens.ts +42 -1
  239. package/corpus/templates/design/agent-native.app-skill.json +4 -0
  240. package/corpus/templates/design/app/components/layout/Layout.tsx +7 -3
  241. package/corpus/templates/design/app/i18n/zh-TW.ts +3 -0
  242. package/corpus/templates/design/app/i18n-data.ts +10 -4
  243. package/corpus/templates/design/app/routes/agent.tsx +2 -1
  244. package/corpus/templates/design/app/routes/settings.tsx +3 -0
  245. package/corpus/templates/design/changelog/2026-07-16-creative-context-library.md +6 -0
  246. package/corpus/templates/design/changelog/2026-07-16-design-agent-chat-no-longer-shows-a-separate-workspace-header.md +6 -0
  247. package/corpus/templates/design/package.json +1 -0
  248. package/corpus/templates/design/server/lib/figma-design-context.ts +5 -335
  249. package/corpus/templates/design/server/lib/figma-node-to-html.ts +1 -1859
  250. package/corpus/templates/design/server/lib/import-design-files.ts +6 -8
  251. package/corpus/templates/design/server/plugins/creative-context.ts +31 -0
  252. package/corpus/templates/design/shared/generation-session.ts +7 -0
  253. package/corpus/templates/dispatch/app/i18n-data.ts +3 -3
  254. package/corpus/templates/forms/app/i18n/en-US.ts +3 -3
  255. package/corpus/templates/macros/app/i18n/en-US.ts +3 -3
  256. package/corpus/templates/mail/app/components/email/EmailThread.tsx +35 -5
  257. package/corpus/templates/mail/app/i18n/en-US.ts +3 -3
  258. package/corpus/templates/mail/changelog/2026-07-16-mail-previews-now-expand-to-show-the-full-message-without-an.md +6 -0
  259. package/corpus/templates/plan/.agents/skills/visual-plan/SKILL.md +30 -11
  260. package/corpus/templates/plan/AGENTS.md +21 -1
  261. package/corpus/templates/plan/actions/get-visual-plan.ts +1 -1
  262. package/corpus/templates/plan/actions/patch-visual-plan-source.ts +161 -0
  263. package/corpus/templates/plan/actions/read-visual-plan-source.ts +1 -1
  264. package/corpus/templates/plan/actions/update-visual-plan.ts +126 -10
  265. package/corpus/templates/plan/app/hooks/use-plans.ts +2 -0
  266. package/corpus/templates/plan/app/i18n/en-US.ts +3 -3
  267. package/corpus/templates/plan/app/pages/PlansPage.tsx +65 -62
  268. package/corpus/templates/plan/changelog/2026-07-16-local-plan-previews-now-load-annotations-containing-html-lik.md +6 -0
  269. package/corpus/templates/plan/changelog/2026-07-16-plan-agents-now-prevent-stale-edits-from-overwriting-newer-p.md +6 -0
  270. package/corpus/templates/plan/server/plan-mdx.ts +75 -2
  271. package/corpus/templates/slides/.agents/skills/create-deck/SKILL.md +21 -4
  272. package/corpus/templates/slides/.agents/skills/creative-context/SKILL.md +122 -0
  273. package/corpus/templates/slides/.agents/skills/design-systems/SKILL.md +11 -0
  274. package/corpus/templates/slides/.agents/skills/slide-editing/SKILL.md +12 -3
  275. package/corpus/templates/slides/AGENTS.md +6 -0
  276. package/corpus/templates/slides/actions/add-slide.ts +230 -14
  277. package/corpus/templates/slides/actions/clone-context-slide.ts +302 -0
  278. package/corpus/templates/slides/actions/create-deck.ts +130 -0
  279. package/corpus/templates/slides/actions/extract-pdf.ts +6 -2
  280. package/corpus/templates/slides/actions/import-file.ts +5 -4
  281. package/corpus/templates/slides/actions/patch-deck.ts +200 -10
  282. package/corpus/templates/slides/actions/update-slide.ts +208 -15
  283. package/corpus/templates/slides/app/components/layout/Layout.tsx +2 -0
  284. package/corpus/templates/slides/app/components/visual-editor/CanvasCommentPins.tsx +16 -1
  285. package/corpus/templates/slides/app/i18n/ar-SA.ts +3 -0
  286. package/corpus/templates/slides/app/i18n/de-DE.ts +3 -0
  287. package/corpus/templates/slides/app/i18n/en-US.ts +6 -3
  288. package/corpus/templates/slides/app/i18n/es-ES.ts +3 -0
  289. package/corpus/templates/slides/app/i18n/fr-FR.ts +3 -0
  290. package/corpus/templates/slides/app/i18n/hi-IN.ts +3 -0
  291. package/corpus/templates/slides/app/i18n/ja-JP.ts +3 -0
  292. package/corpus/templates/slides/app/i18n/ko-KR.ts +3 -0
  293. package/corpus/templates/slides/app/i18n/pt-BR.ts +3 -0
  294. package/corpus/templates/slides/app/i18n/zh-CN.ts +3 -0
  295. package/corpus/templates/slides/app/i18n/zh-TW.ts +3 -0
  296. package/corpus/templates/slides/app/lib/validate-native-slide-html.ts +176 -0
  297. package/corpus/templates/slides/app/routes/agent.tsx +7 -1
  298. package/corpus/templates/slides/app/routes/settings.tsx +3 -0
  299. package/corpus/templates/slides/changelog/2026-07-16-creative-context-library.md +6 -0
  300. package/corpus/templates/slides/changelog/2026-07-16-google-slides-native-cloning.md +6 -0
  301. package/corpus/templates/slides/package.json +1 -0
  302. package/corpus/templates/slides/server/handlers/import/docx-parser.ts +4 -85
  303. package/corpus/templates/slides/server/handlers/import/pptx-parser.ts +7 -421
  304. package/corpus/templates/slides/server/plugins/creative-context.ts +166 -0
  305. package/dist/agent/engine/credential-errors.d.ts +1 -1
  306. package/dist/agent/engine/credential-errors.d.ts.map +1 -1
  307. package/dist/agent/engine/credential-errors.js +2 -2
  308. package/dist/agent/engine/credential-errors.js.map +1 -1
  309. package/dist/agent/production-agent.d.ts.map +1 -1
  310. package/dist/agent/production-agent.js +25 -0
  311. package/dist/agent/production-agent.js.map +1 -1
  312. package/dist/agent/run-store.d.ts.map +1 -1
  313. package/dist/agent/run-store.js +12 -2
  314. package/dist/agent/run-store.js.map +1 -1
  315. package/dist/cli/create.d.ts.map +1 -1
  316. package/dist/cli/create.js +1 -0
  317. package/dist/cli/create.js.map +1 -1
  318. package/dist/cli/skills-content/visual-plan-skill.d.ts +1 -1
  319. package/dist/cli/skills-content/visual-plan-skill.d.ts.map +1 -1
  320. package/dist/cli/skills-content/visual-plan-skill.js +30 -11
  321. package/dist/cli/skills-content/visual-plan-skill.js.map +1 -1
  322. package/dist/cli/templates-meta.d.ts.map +1 -1
  323. package/dist/cli/templates-meta.js +4 -3
  324. package/dist/cli/templates-meta.js.map +1 -1
  325. package/dist/client/AgentAskPopover.d.ts +11 -0
  326. package/dist/client/AgentAskPopover.d.ts.map +1 -0
  327. package/dist/client/AgentAskPopover.js +30 -0
  328. package/dist/client/AgentAskPopover.js.map +1 -0
  329. package/dist/client/AgentChatHome.d.ts +1 -1
  330. package/dist/client/AgentChatHome.d.ts.map +1 -1
  331. package/dist/client/AgentChatHome.js +2 -2
  332. package/dist/client/AgentChatHome.js.map +1 -1
  333. package/dist/client/AgentPanel.d.ts +9 -19
  334. package/dist/client/AgentPanel.d.ts.map +1 -1
  335. package/dist/client/AgentPanel.js +119 -80
  336. package/dist/client/AgentPanel.js.map +1 -1
  337. package/dist/client/AssistantChat.d.ts.map +1 -1
  338. package/dist/client/AssistantChat.js +4 -4
  339. package/dist/client/AssistantChat.js.map +1 -1
  340. package/dist/client/MultiTabAssistantChat.d.ts +3 -9
  341. package/dist/client/MultiTabAssistantChat.d.ts.map +1 -1
  342. package/dist/client/MultiTabAssistantChat.js +49 -189
  343. package/dist/client/MultiTabAssistantChat.js.map +1 -1
  344. package/dist/client/agent-chat-adapter.d.ts.map +1 -1
  345. package/dist/client/agent-chat-adapter.js +12 -1
  346. package/dist/client/agent-chat-adapter.js.map +1 -1
  347. package/dist/client/agent-page/AgentContextTab.d.ts.map +1 -1
  348. package/dist/client/agent-page/AgentContextTab.js +26 -28
  349. package/dist/client/agent-page/AgentContextTab.js.map +1 -1
  350. package/dist/client/agent-page/AgentEmptyState.d.ts +13 -0
  351. package/dist/client/agent-page/AgentEmptyState.d.ts.map +1 -0
  352. package/dist/client/agent-page/AgentEmptyState.js +6 -0
  353. package/dist/client/agent-page/AgentEmptyState.js.map +1 -0
  354. package/dist/client/agent-page/AgentJobsTab.d.ts +1 -1
  355. package/dist/client/agent-page/AgentJobsTab.d.ts.map +1 -1
  356. package/dist/client/agent-page/AgentJobsTab.js +90 -58
  357. package/dist/client/agent-page/AgentJobsTab.js.map +1 -1
  358. package/dist/client/agent-page/AgentTabFrame.d.ts +12 -0
  359. package/dist/client/agent-page/AgentTabFrame.d.ts.map +1 -0
  360. package/dist/client/agent-page/AgentTabFrame.js +7 -0
  361. package/dist/client/agent-page/AgentTabFrame.js.map +1 -0
  362. package/dist/client/agent-page/AgentTabsPage.d.ts +9 -1
  363. package/dist/client/agent-page/AgentTabsPage.d.ts.map +1 -1
  364. package/dist/client/agent-page/AgentTabsPage.js +135 -99
  365. package/dist/client/agent-page/AgentTabsPage.js.map +1 -1
  366. package/dist/client/agent-page/types.d.ts +1 -1
  367. package/dist/client/agent-page/types.d.ts.map +1 -1
  368. package/dist/client/agent-page/types.js.map +1 -1
  369. package/dist/client/analytics.d.ts +10 -3
  370. package/dist/client/analytics.d.ts.map +1 -1
  371. package/dist/client/analytics.js +37 -2
  372. package/dist/client/analytics.js.map +1 -1
  373. package/dist/client/chat/run-recovery.d.ts.map +1 -1
  374. package/dist/client/chat/run-recovery.js +10 -3
  375. package/dist/client/chat/run-recovery.js.map +1 -1
  376. package/dist/client/composer/PromptComposer.d.ts.map +1 -1
  377. package/dist/client/composer/PromptComposer.js +2 -2
  378. package/dist/client/composer/PromptComposer.js.map +1 -1
  379. package/dist/client/composer/TiptapComposer.d.ts.map +1 -1
  380. package/dist/client/composer/TiptapComposer.js +15 -3
  381. package/dist/client/composer/TiptapComposer.js.map +1 -1
  382. package/dist/client/dynamic-suggestions.js +3 -3
  383. package/dist/client/dynamic-suggestions.js.map +1 -1
  384. package/dist/client/index.d.ts +4 -3
  385. package/dist/client/index.d.ts.map +1 -1
  386. package/dist/client/index.js +3 -2
  387. package/dist/client/index.js.map +1 -1
  388. package/dist/client/resources/ResourceTree.d.ts +5 -1
  389. package/dist/client/resources/ResourceTree.d.ts.map +1 -1
  390. package/dist/client/resources/ResourceTree.js +74 -5
  391. package/dist/client/resources/ResourceTree.js.map +1 -1
  392. package/dist/client/resources/ResourcesPanel.d.ts +11 -2
  393. package/dist/client/resources/ResourcesPanel.d.ts.map +1 -1
  394. package/dist/client/resources/ResourcesPanel.js +105 -31
  395. package/dist/client/resources/ResourcesPanel.js.map +1 -1
  396. package/dist/client/session-replay.d.ts +28 -0
  397. package/dist/client/session-replay.d.ts.map +1 -1
  398. package/dist/client/session-replay.js +122 -8
  399. package/dist/client/session-replay.js.map +1 -1
  400. package/dist/client/settings/AutomationsSection.d.ts +3 -1
  401. package/dist/client/settings/AutomationsSection.d.ts.map +1 -1
  402. package/dist/client/settings/AutomationsSection.js +16 -6
  403. package/dist/client/settings/AutomationsSection.js.map +1 -1
  404. package/dist/client/settings/SettingsPanel.d.ts.map +1 -1
  405. package/dist/client/settings/SettingsPanel.js +3 -3
  406. package/dist/client/settings/SettingsPanel.js.map +1 -1
  407. package/dist/client/settings/SettingsTabsPage.d.ts +2 -0
  408. package/dist/client/settings/SettingsTabsPage.d.ts.map +1 -1
  409. package/dist/client/settings/SettingsTabsPage.js.map +1 -1
  410. package/dist/client/settings/agent-settings-search.js +2 -2
  411. package/dist/client/settings/agent-settings-search.js.map +1 -1
  412. package/dist/client/use-chat-threads.d.ts +2 -0
  413. package/dist/client/use-chat-threads.d.ts.map +1 -1
  414. package/dist/client/use-chat-threads.js.map +1 -1
  415. package/dist/collab/routes.d.ts +1 -1
  416. package/dist/connections/catalog.d.ts +41 -7
  417. package/dist/connections/catalog.d.ts.map +1 -1
  418. package/dist/connections/catalog.js +40 -7
  419. package/dist/connections/catalog.js.map +1 -1
  420. package/dist/db/index.d.ts +2 -2
  421. package/dist/db/index.d.ts.map +1 -1
  422. package/dist/db/index.js +2 -2
  423. package/dist/db/index.js.map +1 -1
  424. package/dist/extensions/actions.d.ts.map +1 -1
  425. package/dist/extensions/actions.js +85 -15
  426. package/dist/extensions/actions.js.map +1 -1
  427. package/dist/extensions/content-patch.d.ts +4 -0
  428. package/dist/extensions/content-patch.d.ts.map +1 -1
  429. package/dist/extensions/content-patch.js +18 -0
  430. package/dist/extensions/content-patch.js.map +1 -1
  431. package/dist/extensions/routes.d.ts.map +1 -1
  432. package/dist/extensions/routes.js +14 -0
  433. package/dist/extensions/routes.js.map +1 -1
  434. package/dist/extensions/store.d.ts +1 -0
  435. package/dist/extensions/store.d.ts.map +1 -1
  436. package/dist/extensions/store.js +4 -1
  437. package/dist/extensions/store.js.map +1 -1
  438. package/dist/file-upload/actions/upload-image.d.ts +1 -1
  439. package/dist/index.d.ts +1 -1
  440. package/dist/index.d.ts.map +1 -1
  441. package/dist/index.js +1 -1
  442. package/dist/index.js.map +1 -1
  443. package/dist/ingestion/docx.d.ts +16 -0
  444. package/dist/ingestion/docx.d.ts.map +1 -0
  445. package/dist/ingestion/docx.js +129 -0
  446. package/dist/ingestion/docx.js.map +1 -0
  447. package/dist/ingestion/figma-node-to-html.d.ts +304 -0
  448. package/dist/ingestion/figma-node-to-html.d.ts.map +1 -0
  449. package/dist/ingestion/figma-node-to-html.js +1292 -0
  450. package/dist/ingestion/figma-node-to-html.js.map +1 -0
  451. package/dist/ingestion/figma.d.ts +115 -0
  452. package/dist/ingestion/figma.d.ts.map +1 -0
  453. package/dist/ingestion/figma.js +399 -0
  454. package/dist/ingestion/figma.js.map +1 -0
  455. package/dist/ingestion/index.d.ts +11 -0
  456. package/dist/ingestion/index.d.ts.map +1 -0
  457. package/dist/ingestion/index.js +11 -0
  458. package/dist/ingestion/index.js.map +1 -0
  459. package/dist/ingestion/media.d.ts +36 -0
  460. package/dist/ingestion/media.d.ts.map +1 -0
  461. package/dist/ingestion/media.js +178 -0
  462. package/dist/ingestion/media.js.map +1 -0
  463. package/dist/ingestion/notion.d.ts +12 -0
  464. package/dist/ingestion/notion.d.ts.map +1 -0
  465. package/dist/ingestion/notion.js +104 -0
  466. package/dist/ingestion/notion.js.map +1 -0
  467. package/dist/ingestion/office.d.ts +45 -0
  468. package/dist/ingestion/office.d.ts.map +1 -0
  469. package/dist/ingestion/office.js +141 -0
  470. package/dist/ingestion/office.js.map +1 -0
  471. package/dist/ingestion/orchestration.d.ts +52 -0
  472. package/dist/ingestion/orchestration.d.ts.map +1 -0
  473. package/dist/ingestion/orchestration.js +89 -0
  474. package/dist/ingestion/orchestration.js.map +1 -0
  475. package/dist/ingestion/pptx.d.ts +28 -0
  476. package/dist/ingestion/pptx.d.ts.map +1 -0
  477. package/dist/ingestion/pptx.js +255 -0
  478. package/dist/ingestion/pptx.js.map +1 -0
  479. package/dist/ingestion/selection.d.ts +20 -0
  480. package/dist/ingestion/selection.d.ts.map +1 -0
  481. package/dist/ingestion/selection.js +52 -0
  482. package/dist/ingestion/selection.js.map +1 -0
  483. package/dist/ingestion/website.d.ts +27 -0
  484. package/dist/ingestion/website.d.ts.map +1 -0
  485. package/dist/ingestion/website.js +100 -0
  486. package/dist/ingestion/website.js.map +1 -0
  487. package/dist/integrations/plugin.d.ts.map +1 -1
  488. package/dist/integrations/plugin.js +32 -27
  489. package/dist/integrations/plugin.js.map +1 -1
  490. package/dist/localization/default-messages.d.ts +22 -0
  491. package/dist/localization/default-messages.d.ts.map +1 -1
  492. package/dist/localization/default-messages.js +31 -9
  493. package/dist/localization/default-messages.js.map +1 -1
  494. package/dist/notifications/routes.d.ts +1 -1
  495. package/dist/observability/hosted-model-experiment.d.ts +39 -0
  496. package/dist/observability/hosted-model-experiment.d.ts.map +1 -0
  497. package/dist/observability/hosted-model-experiment.js +90 -0
  498. package/dist/observability/hosted-model-experiment.js.map +1 -0
  499. package/dist/observability/traces.d.ts.map +1 -1
  500. package/dist/observability/traces.js +5 -3
  501. package/dist/observability/traces.js.map +1 -1
  502. package/dist/progress/routes.d.ts +1 -1
  503. package/dist/provider-api/index.d.ts +35 -4
  504. package/dist/provider-api/index.d.ts.map +1 -1
  505. package/dist/provider-api/index.js +339 -8
  506. package/dist/provider-api/index.js.map +1 -1
  507. package/dist/scripts/agent-engines/list-agent-engines.d.ts.map +1 -1
  508. package/dist/scripts/agent-engines/list-agent-engines.js +18 -1
  509. package/dist/scripts/agent-engines/list-agent-engines.js.map +1 -1
  510. package/dist/search-utils/index.d.ts +12 -0
  511. package/dist/search-utils/index.d.ts.map +1 -0
  512. package/dist/search-utils/index.js +95 -0
  513. package/dist/search-utils/index.js.map +1 -0
  514. package/dist/secrets/register-framework-secrets.d.ts.map +1 -1
  515. package/dist/secrets/register-framework-secrets.js +57 -0
  516. package/dist/secrets/register-framework-secrets.js.map +1 -1
  517. package/dist/server/action-discovery.d.ts +8 -0
  518. package/dist/server/action-discovery.d.ts.map +1 -1
  519. package/dist/server/action-discovery.js +26 -9
  520. package/dist/server/action-discovery.js.map +1 -1
  521. package/dist/server/agent-chat/framework-prompts.js +2 -2
  522. package/dist/server/agent-chat/framework-prompts.js.map +1 -1
  523. package/dist/server/agent-chat/prompt-resources.d.ts +19 -0
  524. package/dist/server/agent-chat/prompt-resources.d.ts.map +1 -1
  525. package/dist/server/agent-chat/prompt-resources.js +95 -0
  526. package/dist/server/agent-chat/prompt-resources.js.map +1 -1
  527. package/dist/server/agent-chat-plugin.d.ts.map +1 -1
  528. package/dist/server/agent-chat-plugin.js +7 -0
  529. package/dist/server/agent-chat-plugin.js.map +1 -1
  530. package/dist/server/agent-engine-api-key-route.d.ts +1 -1
  531. package/dist/server/core-routes-plugin.d.ts.map +1 -1
  532. package/dist/server/core-routes-plugin.js +5 -0
  533. package/dist/server/core-routes-plugin.js.map +1 -1
  534. package/dist/server/index.d.ts +5 -1
  535. package/dist/server/index.d.ts.map +1 -1
  536. package/dist/server/index.js +5 -1
  537. package/dist/server/index.js.map +1 -1
  538. package/dist/server/workspace-provider-oauth.d.ts +48 -0
  539. package/dist/server/workspace-provider-oauth.d.ts.map +1 -0
  540. package/dist/server/workspace-provider-oauth.js +415 -0
  541. package/dist/server/workspace-provider-oauth.js.map +1 -0
  542. package/dist/styles/agent-native.css +9 -0
  543. package/dist/templates/chat/app/i18n/en-US.ts +3 -3
  544. package/dist/templates/chat/app/lib/agent-page.tsx +10 -1
  545. package/dist/templates/default/app/i18n/en-US.ts +3 -3
  546. package/dist/templates/workspace-core/.agents/skills/extensions/SKILL.md +14 -5
  547. package/dist/templates/workspace-root/.env.example +12 -0
  548. package/dist/workspace-connections/index.d.ts +1 -0
  549. package/dist/workspace-connections/index.d.ts.map +1 -1
  550. package/dist/workspace-connections/index.js +1 -0
  551. package/dist/workspace-connections/index.js.map +1 -1
  552. package/dist/workspace-connections/lifecycle.d.ts +16 -0
  553. package/dist/workspace-connections/lifecycle.d.ts.map +1 -0
  554. package/dist/workspace-connections/lifecycle.js +14 -0
  555. package/dist/workspace-connections/lifecycle.js.map +1 -0
  556. package/dist/workspace-connections/store.d.ts.map +1 -1
  557. package/dist/workspace-connections/store.js +16 -0
  558. package/dist/workspace-connections/store.js.map +1 -1
  559. package/package.json +10 -3
  560. package/src/templates/chat/app/i18n/en-US.ts +3 -3
  561. package/src/templates/chat/app/lib/agent-page.spec.tsx +10 -1
  562. package/src/templates/chat/app/lib/agent-page.tsx +10 -1
  563. package/src/templates/default/app/i18n/en-US.ts +3 -3
  564. package/src/templates/workspace-core/.agents/skills/extensions/SKILL.md +14 -5
  565. package/src/templates/workspace-root/.env.example +12 -0
@@ -0,0 +1,1292 @@
1
+ /**
2
+ * Figma node JSON -> HTML mapper.
3
+ *
4
+ * Input is the `document` subtree returned by
5
+ * `GET /v1/files/:fileKey/nodes?ids=...&geometry=paths` (or the file's root
6
+ * `document` node). Output is a self-contained HTML fragment using absolute
7
+ * positioning + inline styles, matching Figma's own canvas model 1:1 rather
8
+ * than reconstructing a semantic/Tailwind layout — the goal is pixel fidelity
9
+ * for an imported snapshot, not idiomatic hand-authored markup.
10
+ *
11
+ * This module is pure and synchronous: it never calls the network. The
12
+ * caller (an action) is responsible for:
13
+ * 1. Fetching the node JSON from the Figma REST API.
14
+ * 2. Calling `collectFallbackNodeIds` / `collectImageFillRefs` to find out
15
+ * which nodes need a rendered PNG fallback and which image fills need
16
+ * resolved URLs.
17
+ * 3. Fetching those via `/v1/images/:fileKey` (fallback renders) and
18
+ * `/v1/files/:fileKey/images` (fill ref -> URL map).
19
+ * 4. Calling `mapFigmaNodeToHtml` with the resulting maps.
20
+ *
21
+ * ## Pixel-perfect property coverage
22
+ *
23
+ * | Property | Fidelity | Notes |
24
+ * | ------------------------------------------- | ------------- | ----- |
25
+ * | Position/size (absoluteBoundingBox) | exact | frame-relative |
26
+ * | Auto-layout (flex*) | exact | Figma auto-layout IS flexbox |
27
+ * | Text font/size/weight/case/decoration/align | exact | |
28
+ * | Line-height (px vs percent-of-font-size) | exact | resolved to px |
29
+ * | Letter-spacing | exact | already px in REST API |
30
+ * | Solid fills | exact | |
31
+ * | Gradient fills (angle/position) | exact (linear)/approximated (radial/angular/diamond) | derived from gradientHandlePositions, not a default angle |
32
+ * | Multiple fills (layering) | exact | reversed to match CSS background-image stacking |
33
+ * | Image fills (scale modes) | exact (FILL/FIT/TILE/STRETCH-axis-aligned) / approximated (skewed imageTransform) | |
34
+ * | Strokes (uniform, align) | exact | CENTER via outline+negative offset, INSIDE via inset box-shadow, OUTSIDE via outline |
35
+ * | Strokes (per-side weights) | approximated | CSS has no per-side outline; falls back to per-side `border` (inside-only) |
36
+ * | Corner radii (uniform + per-corner) | exact | |
37
+ * | Effects: drop/inner shadow | exact | |
38
+ * | Effects: layer/background blur | approximated | Figma <-> CSS blur radius scale is not publicly specified as 1:1 |
39
+ * | Opacity | exact | |
40
+ * | Blend modes (CSS-supported) | exact | |
41
+ * | Blend modes (Figma-only: LINEAR_BURN/DODGE/LIGHTER/DARKER) | approximated | mapped to closest CSS equivalent |
42
+ * | clipsContent | exact | overflow: hidden |
43
+ * | Rotation | approximated | pivots about the bounding-box center (see below) |
44
+ * | Vector networks / boolean ops / unsupported types | image fallback | never approximated structurally |
45
+ *
46
+ * ### Rotation caveat
47
+ * The REST API docs describe `rotation` as being in degrees, but the field
48
+ * is empirically returned in RADIANS (verified against known authored
49
+ * rotations via the Plugin API); this mapper converts it to degrees before
50
+ * use. `absoluteBoundingBox` is the *already-rotated* axis-aligned bounding
51
+ * box —
52
+ * Figma does not expose the pre-rotation box directly. We reconstruct the
53
+ * unrotated box by treating the AABB's center as invariant under rotation
54
+ * (true for a shape rotated about its own center) and rotate the CSS element
55
+ * about `transform-origin: center` by `-rotation` degrees (Figma's rotation
56
+ * is clockwise-negative relative to CSS's clockwise-positive convention).
57
+ * This is exact when Figma pivots rotation about the shape's center and only
58
+ * approximated if Figma's internal pivot differs (rare in practice; visually
59
+ * indistinguishable in the overwhelming majority of designs). A fully exact
60
+ * alternative would consume `relativeTransform` as a CSS `matrix()` directly,
61
+ * which is a documented follow-up if a specific design surfaces a visible
62
+ * mismatch.
63
+ */
64
+ const UNSUPPORTED_STRUCTURAL_TYPES = new Set([
65
+ "BOOLEAN_OPERATION",
66
+ "VECTOR",
67
+ "STAR",
68
+ "REGULAR_POLYGON",
69
+ "SLICE",
70
+ "STICKY",
71
+ "SHAPE_WITH_TEXT",
72
+ "CONNECTOR",
73
+ "WASHI_TAPE",
74
+ "TABLE",
75
+ ]);
76
+ const SUPPORTED_CONTAINER_TYPES = new Set([
77
+ "FRAME",
78
+ "GROUP",
79
+ "COMPONENT",
80
+ "COMPONENT_SET",
81
+ "INSTANCE",
82
+ "SECTION",
83
+ ]);
84
+ const MAX_FIGMA_NODE_COUNT = 75_000;
85
+ const MAX_FIGMA_NODE_DEPTH = 256;
86
+ const MAX_METADATA_ATTRIBUTE_CHARS = 16_384;
87
+ // ---------------------------------------------------------------------------
88
+ // Formatting helpers
89
+ // ---------------------------------------------------------------------------
90
+ function round(value, precision = 2) {
91
+ const factor = 10 ** precision;
92
+ return Math.round(value * factor) / factor;
93
+ }
94
+ function px(value, precision = 2) {
95
+ if (typeof value !== "number" || !Number.isFinite(value))
96
+ return undefined;
97
+ return `${round(value, precision)}px`;
98
+ }
99
+ function colorToCss(color, opacityMul = 1) {
100
+ if (!color)
101
+ return null;
102
+ const r = Math.round((color.r ?? 0) * 255);
103
+ const g = Math.round((color.g ?? 0) * 255);
104
+ const b = Math.round((color.b ?? 0) * 255);
105
+ const a = round((color.a ?? 1) * opacityMul, 4);
106
+ return `rgba(${r}, ${g}, ${b}, ${a})`;
107
+ }
108
+ function escapeHtml(value) {
109
+ return value
110
+ .replace(/&/g, "&amp;")
111
+ .replace(/</g, "&lt;")
112
+ .replace(/>/g, "&gt;")
113
+ .replace(/"/g, "&quot;");
114
+ }
115
+ function escapeAttr(value) {
116
+ return escapeHtml(value);
117
+ }
118
+ function metadataAttr(name, value, node, tracker) {
119
+ if (value === undefined || value === null)
120
+ return "";
121
+ let serialized;
122
+ try {
123
+ serialized = typeof value === "string" ? value : JSON.stringify(value);
124
+ }
125
+ catch {
126
+ tracker.record(node, "approximated", `${name} metadata could not be serialized and was omitted.`);
127
+ return "";
128
+ }
129
+ if (serialized.length > MAX_METADATA_ATTRIBUTE_CHARS) {
130
+ tracker.record(node, "approximated", `${name} metadata exceeded ${MAX_METADATA_ATTRIBUTE_CHARS} characters and was omitted.`);
131
+ return "";
132
+ }
133
+ return ` ${name}="${escapeAttr(serialized)}"`;
134
+ }
135
+ /**
136
+ * Builds the CSS text for a `style="..."` attribute AND escapes it for HTML
137
+ * attribute context. This matters because at least one style value we emit
138
+ * legitimately contains a literal double-quote character: font-family values
139
+ * are built as `"Inter", sans-serif` (CSS requires quoting family names with
140
+ * spaces). Without escaping here, that embedded `"` prematurely terminates
141
+ * the enclosing `style="..."` attribute the moment a browser (or any other
142
+ * HTML parser) reads it -- silently dropping every style declared after
143
+ * font-family in object-key order (font-size, font-weight, line-height,
144
+ * text-align, and the text node's own `display: flex` used to emulate
145
+ * vertical alignment). The visible symptom is text rendering at the
146
+ * browser's default font/size instead of the mapped Figma typography, with
147
+ * no error anywhere -- caught here via a real headless-browser render that
148
+ * showed a Figma TEXT node's own style attribute silently truncated at
149
+ * `font-family: "`.
150
+ */
151
+ function styleAttr(styles) {
152
+ const parts = Object.entries(styles)
153
+ .filter((entry) => typeof entry[1] === "string")
154
+ .map(([key, value]) => `${key}: ${value}`);
155
+ return escapeAttr(parts.join("; "));
156
+ }
157
+ // ---------------------------------------------------------------------------
158
+ // Fidelity report builder
159
+ // ---------------------------------------------------------------------------
160
+ class FidelityTracker {
161
+ entries = new Map();
162
+ record(node, level, note) {
163
+ const existing = this.entries.get(node.id);
164
+ if (existing) {
165
+ // Never downgrade an image-fallback entry, and never upgrade below the
166
+ // worst level recorded for this node.
167
+ const rank = {
168
+ exact: 0,
169
+ approximated: 1,
170
+ "image-fallback": 2,
171
+ };
172
+ if (rank[level] > rank[existing.level])
173
+ existing.level = level;
174
+ existing.notes.push(note);
175
+ return;
176
+ }
177
+ this.entries.set(node.id, {
178
+ nodeId: node.id,
179
+ nodeName: node.name ?? node.id,
180
+ nodeType: node.type,
181
+ level,
182
+ notes: [note],
183
+ });
184
+ }
185
+ build() {
186
+ const entries = [...this.entries.values()];
187
+ const summary = entries.reduce((acc, entry) => {
188
+ if (entry.level === "exact")
189
+ acc.exact += 1;
190
+ else if (entry.level === "approximated")
191
+ acc.approximated += 1;
192
+ else
193
+ acc.imageFallback += 1;
194
+ return acc;
195
+ }, { exact: 0, approximated: 0, imageFallback: 0 });
196
+ return { entries, summary };
197
+ }
198
+ }
199
+ function resolveGradientGeometry(paint) {
200
+ const handles = paint.gradientHandlePositions;
201
+ if (!handles || handles.length < 3)
202
+ return null;
203
+ return { start: handles[0], end: handles[1], width: handles[2] };
204
+ }
205
+ /**
206
+ * Derive a CSS `linear-gradient()` angle (degrees) from Figma's normalized
207
+ * `gradientHandlePositions`. Handle positions are normalized independently in
208
+ * x and y (0..1 relative to the node's bounding box), so the angle must be
209
+ * computed in actual pixel space using the node's real width/height —
210
+ * otherwise a non-square box silently distorts the angle.
211
+ *
212
+ * Verified against Figma's documented identity handles
213
+ * (start=(0,0.5), end=(1,0.5), width=(1,0), i.e. a plain left-to-right
214
+ * gradient) which must resolve to CSS `90deg` ("to right"):
215
+ * dx = 1*w, dy = 0 -> atan2(0, dx) = 0deg -> +90 = 90deg. Matches.
216
+ * And a top-to-bottom gradient (start=(0.5,0), end=(0.5,1)) must resolve to
217
+ * CSS `180deg` ("to bottom"):
218
+ * dx = 0, dy = 1*h -> atan2(dy, 0) = 90deg -> +90 = 180deg. Matches.
219
+ */
220
+ export function gradientAngleDegrees(paint, box) {
221
+ const geometry = resolveGradientGeometry(paint);
222
+ if (!geometry)
223
+ return null;
224
+ const dx = (geometry.end.x - geometry.start.x) * box.width;
225
+ const dy = (geometry.end.y - geometry.start.y) * box.height;
226
+ const angleRad = Math.atan2(dy, dx);
227
+ const angleDeg = (angleRad * 180) / Math.PI + 90;
228
+ return ((angleDeg % 360) + 360) % 360;
229
+ }
230
+ function gradientStopsCss(paint, remapPosition) {
231
+ const stops = paint.gradientStops ?? [];
232
+ return stops
233
+ .map((stop) => {
234
+ const color = colorToCss(stop.color, paint.opacity ?? 1) ?? "transparent";
235
+ const position = remapPosition
236
+ ? remapPosition(stop.position)
237
+ : stop.position;
238
+ return `${color} ${round(position * 100, 2)}%`;
239
+ })
240
+ .join(", ");
241
+ }
242
+ /**
243
+ * CSS `linear-gradient(angle, ...)` always stretches its 0%/100% stops
244
+ * across the box's FULL diagonal extent at that angle (the CSS spec's
245
+ * "gradient line" always spans corner-to-corner) -- it has no way to say
246
+ * "start partway in, end partway in" the way Figma's actual gradient handles
247
+ * can (a designer can drag the start/end handles anywhere, including short
248
+ * of the shape's edges, or past them). Figma's own stop positions are
249
+ * fractions of the literal start-handle-to-end-handle distance, which only
250
+ * happens to coincide with the CSS full-box span when the handles are
251
+ * dragged exactly corner-to-corner -- a common case, but far from the only
252
+ * one, and the divergence gets worse the more the box's aspect ratio departs
253
+ * from square (rotated/skewed handles included, e.g. gradientTransform-authored
254
+ * paints). This projects each Figma stop's real pixel position onto the same
255
+ * angle CSS will use and re-expresses it as a percentage of the CSS line's
256
+ * length, so a partial/offset gradient renders at the same actual pixel
257
+ * positions Figma draws it at instead of silently stretching to fill the box.
258
+ */
259
+ function remapLinearStopPosition(geometry, box, angleDeg) {
260
+ const angleRad = (angleDeg * Math.PI) / 180;
261
+ const ux = Math.sin(angleRad);
262
+ const uy = -Math.cos(angleRad);
263
+ const lineLength = box.width * Math.abs(ux) + box.height * Math.abs(uy);
264
+ if (lineLength < 1e-6)
265
+ return (position) => position;
266
+ const startPx = {
267
+ x: geometry.start.x * box.width,
268
+ y: geometry.start.y * box.height,
269
+ };
270
+ const endPx = {
271
+ x: geometry.end.x * box.width,
272
+ y: geometry.end.y * box.height,
273
+ };
274
+ const centerX = box.width / 2;
275
+ const centerY = box.height / 2;
276
+ return (position) => {
277
+ const pointX = startPx.x + position * (endPx.x - startPx.x);
278
+ const pointY = startPx.y + position * (endPx.y - startPx.y);
279
+ const projected = (pointX - centerX) * ux + (pointY - centerY) * uy;
280
+ return (projected + lineLength / 2) / lineLength;
281
+ };
282
+ }
283
+ function vectorLength(from, to, box) {
284
+ const dx = (to.x - from.x) * box.width;
285
+ const dy = (to.y - from.y) * box.height;
286
+ return Math.sqrt(dx * dx + dy * dy);
287
+ }
288
+ /**
289
+ * Convert one Figma paint layer to a CSS `background-image` value (or plain
290
+ * color for a SOLID paint used standalone). Returns null for paints that
291
+ * cannot be expressed as a background-image (handled elsewhere).
292
+ */
293
+ function paintToCssImage(paint, box, tracker, node) {
294
+ if (paint.visible === false)
295
+ return null;
296
+ const stops = gradientStopsCss(paint);
297
+ if (!stops)
298
+ return null;
299
+ switch (paint.type) {
300
+ case "GRADIENT_LINEAR": {
301
+ const angle = gradientAngleDegrees(paint, box);
302
+ const geometry = resolveGradientGeometry(paint);
303
+ // Re-express Figma's handle-relative stop positions as percentages of
304
+ // CSS's own full-box gradient line (see remapLinearStopPosition) so a
305
+ // gradient whose handles don't span exactly corner-to-corner still
306
+ // lands its color transitions at the same real pixel positions Figma
307
+ // draws them at, instead of being stretched to fill the whole box.
308
+ const linearStops = angle !== null && geometry
309
+ ? gradientStopsCss(paint, remapLinearStopPosition(geometry, box, angle))
310
+ : stops;
311
+ tracker.record(node, "exact", "Linear gradient angle and stop offsets derived from gradientHandlePositions.");
312
+ return `linear-gradient(${round(angle ?? 90, 2)}deg, ${linearStops})`;
313
+ }
314
+ case "GRADIENT_RADIAL": {
315
+ const geometry = resolveGradientGeometry(paint);
316
+ if (!geometry)
317
+ return `radial-gradient(${stops})`;
318
+ const cx = round(geometry.start.x * 100, 2);
319
+ const cy = round(geometry.start.y * 100, 2);
320
+ // Figma's handle[1] ("end") is the radius vector along the gradient's
321
+ // own primary axis; handle[2] ("width") is the perpendicular radius.
322
+ // For an axis-aligned box those map directly to the ellipse's
323
+ // horizontal/vertical radii -- swapping them (as a prior version of
324
+ // this code did) silently rotates the ellipse 90 degrees, which is
325
+ // invisible for a square box but produces a badly wrong bowtie-shaped
326
+ // gradient for any non-square rectangle (the common case).
327
+ const radiusX = vectorLength(geometry.start, geometry.end, box);
328
+ const radiusY = vectorLength(geometry.start, geometry.width, box);
329
+ tracker.record(node, "approximated", "Radial gradient rendered as an axis-aligned ellipse sized from gradientHandlePositions; rotated/skewed radial gradients are not expressible in CSS radial-gradient().");
330
+ return `radial-gradient(ellipse ${round(radiusX, 2)}px ${round(radiusY, 2)}px at ${cx}% ${cy}%, ${stops})`;
331
+ }
332
+ case "GRADIENT_ANGULAR": {
333
+ const geometry = resolveGradientGeometry(paint);
334
+ const cx = geometry ? round(geometry.start.x * 100, 2) : 50;
335
+ const cy = geometry ? round(geometry.start.y * 100, 2) : 50;
336
+ const fromAngle = geometry ? gradientAngleDegrees(paint, box) : 0;
337
+ tracker.record(node, "approximated", "Conic (angular) gradient start angle derived from gradientHandlePositions using the same angle formula as linear gradients; CSS conic-gradient() has no elliptical distortion so non-uniform boxes may render slightly differently than Figma.");
338
+ return `conic-gradient(from ${round(fromAngle ?? 0, 2)}deg at ${cx}% ${cy}%, ${stops})`;
339
+ }
340
+ case "GRADIENT_DIAMOND": {
341
+ const geometry = resolveGradientGeometry(paint);
342
+ const cx = geometry ? round(geometry.start.x * 100, 2) : 50;
343
+ const cy = geometry ? round(geometry.start.y * 100, 2) : 50;
344
+ // Same handle-to-axis mapping fix as GRADIENT_RADIAL above: handle[1]
345
+ // ("end") is the primary-axis radius, handle[2] ("width") the
346
+ // perpendicular one.
347
+ const radiusX = geometry
348
+ ? vectorLength(geometry.start, geometry.end, box)
349
+ : box.width / 2;
350
+ const radiusY = geometry
351
+ ? vectorLength(geometry.start, geometry.width, box)
352
+ : box.height / 2;
353
+ tracker.record(node, "approximated", "Diamond gradient has no CSS equivalent; approximated as an axis-aligned elliptical radial-gradient sized from gradientHandlePositions. True diamond (rotated-square) falloff is not reproduced.");
354
+ return `radial-gradient(ellipse ${round(radiusX, 2)}px ${round(radiusY, 2)}px at ${cx}% ${cy}%, ${stops})`;
355
+ }
356
+ default:
357
+ return null;
358
+ }
359
+ }
360
+ function imageScaleModeCss(paint, node, tracker) {
361
+ const transform = paint.imageTransform;
362
+ const isAxisAligned = !transform ||
363
+ (Math.abs(transform[0][1]) < 1e-6 && Math.abs(transform[1][0]) < 1e-6);
364
+ if (!isAxisAligned) {
365
+ tracker.record(node, "approximated", "Image fill has a non-axis-aligned imageTransform (rotated/skewed crop); approximated using the scale-mode-only CSS mapping without the transform matrix.");
366
+ }
367
+ switch (paint.scaleMode) {
368
+ case "FILL":
369
+ return { size: "cover", position: "center", repeat: "no-repeat" };
370
+ case "FIT":
371
+ return { size: "contain", position: "center", repeat: "no-repeat" };
372
+ case "TILE":
373
+ return { size: "auto", position: "top left", repeat: "repeat" };
374
+ case "STRETCH":
375
+ return { size: "100% 100%", position: "center", repeat: "no-repeat" };
376
+ default:
377
+ return { size: "cover", position: "center", repeat: "no-repeat" };
378
+ }
379
+ }
380
+ /**
381
+ * Build the background-* properties for a node's fill stack. Figma paints
382
+ * fills bottom-to-top (index 0 is the bottommost layer); CSS
383
+ * `background-image` layers top-to-bottom (first value on top), so the
384
+ * stack is reversed here to preserve visual order. A solid fill above other
385
+ * layers is expressed as a flat `linear-gradient(color, color)` since CSS
386
+ * `background-color` always paints *beneath every* background-image and
387
+ * cannot be interleaved mid-stack.
388
+ */
389
+ function buildFills(node, fills, box, options, tracker, isTextNode) {
390
+ const visible = (fills ?? []).filter((fill) => fill.visible !== false);
391
+ if (visible.length === 0)
392
+ return {};
393
+ if (isTextNode) {
394
+ // Text color comes from the topmost visible SOLID fill; gradient/image
395
+ // text fills are a CSS `background-clip: text` trick we intentionally
396
+ // skip for now (rare in practice) and record as approximated.
397
+ const solid = [...visible].reverse().find((fill) => fill.type === "SOLID");
398
+ if (solid) {
399
+ return {
400
+ color: colorToCss(solid.color, solid.opacity ?? 1) ?? undefined,
401
+ };
402
+ }
403
+ tracker.record(node, "approximated", "Text fill is a gradient/image, not a solid color; rendered with the default text color instead of a background-clip: text gradient.");
404
+ return {};
405
+ }
406
+ const images = [];
407
+ const sizes = [];
408
+ const positions = [];
409
+ const repeats = [];
410
+ let backgroundColor;
411
+ // Reverse so the topmost Figma fill becomes the first (topmost) CSS layer.
412
+ const ordered = [...visible].reverse();
413
+ for (let index = 0; index < ordered.length; index += 1) {
414
+ const fill = ordered[index];
415
+ const isBottommost = index === ordered.length - 1;
416
+ if (fill.type === "SOLID") {
417
+ const color = colorToCss(fill.color, fill.opacity ?? 1);
418
+ if (!color)
419
+ continue;
420
+ if (isBottommost) {
421
+ // A bottom-most solid always paints beneath every background-image
422
+ // layer, so it can always become plain backgroundColor regardless of
423
+ // how many gradient/image layers are stacked above it.
424
+ backgroundColor = color;
425
+ }
426
+ else {
427
+ // Solid above other layers: express as a flat gradient so it stacks
428
+ // in the correct z-order alongside gradient/image layers.
429
+ images.push(`linear-gradient(${color}, ${color})`);
430
+ sizes.push("100% 100%");
431
+ positions.push("center");
432
+ repeats.push("no-repeat");
433
+ }
434
+ continue;
435
+ }
436
+ if (fill.type === "IMAGE") {
437
+ const url = fill.imageRef
438
+ ? options.imageFillUrls?.[fill.imageRef]
439
+ : undefined;
440
+ if (!url) {
441
+ tracker.record(node, "approximated", `Image fill imageRef "${fill.imageRef ?? "unknown"}" had no resolved URL; layer omitted.`);
442
+ continue;
443
+ }
444
+ const mode = imageScaleModeCss(fill, node, tracker);
445
+ images.push(`url("${url}")`);
446
+ sizes.push(mode.size);
447
+ positions.push(mode.position);
448
+ repeats.push(mode.repeat);
449
+ continue;
450
+ }
451
+ const cssImage = paintToCssImage(fill, box, tracker, node);
452
+ if (cssImage) {
453
+ images.push(cssImage);
454
+ sizes.push("100% 100%");
455
+ positions.push("center");
456
+ repeats.push("no-repeat");
457
+ }
458
+ }
459
+ const result = {};
460
+ if (backgroundColor)
461
+ result.backgroundColor = backgroundColor;
462
+ if (images.length > 0) {
463
+ result.backgroundImage = images.join(", ");
464
+ result.backgroundSize = sizes.join(", ");
465
+ result.backgroundPosition = positions.join(", ");
466
+ result.backgroundRepeat = repeats.join(", ");
467
+ }
468
+ return result;
469
+ }
470
+ function buildStrokes(node, tracker) {
471
+ const strokes = (node.strokes ?? []).filter((stroke) => stroke.visible !== false);
472
+ if (strokes.length === 0)
473
+ return { styles: {} };
474
+ const first = strokes[0];
475
+ const color = colorToCss(first.color, first.opacity ?? 1) ?? "rgba(0, 0, 0, 1)";
476
+ const iw = node.individualStrokeWeights;
477
+ const hasPerSide = iw &&
478
+ (iw.top !== undefined ||
479
+ iw.right !== undefined ||
480
+ iw.bottom !== undefined ||
481
+ iw.left !== undefined);
482
+ const uniformWeight = node.strokeWeight ?? 0;
483
+ if (hasPerSide) {
484
+ // CSS `outline`/inset-`box-shadow` tricks are single-weight only; per-side
485
+ // stroke weights can only be expressed as a real per-side `border`, which
486
+ // always renders fully inside the border-box regardless of strokeAlign.
487
+ // This is exact for INSIDE and an approximation for CENTER/OUTSIDE.
488
+ const top = iw?.top ?? uniformWeight;
489
+ const right = iw?.right ?? uniformWeight;
490
+ const bottom = iw?.bottom ?? uniformWeight;
491
+ const left = iw?.left ?? uniformWeight;
492
+ tracker.record(node, node.strokeAlign === "INSIDE" || !node.strokeAlign
493
+ ? "exact"
494
+ : "approximated", `Per-side stroke weights rendered as CSS border (inside-aligned); strokeAlign="${node.strokeAlign ?? "INSIDE"}" cannot vary per-side with outline tricks.`);
495
+ return {
496
+ styles: {
497
+ "border-top": top ? `${px(top)} solid ${color}` : undefined,
498
+ "border-right": right ? `${px(right)} solid ${color}` : undefined,
499
+ "border-bottom": bottom ? `${px(bottom)} solid ${color}` : undefined,
500
+ "border-left": left ? `${px(left)} solid ${color}` : undefined,
501
+ },
502
+ };
503
+ }
504
+ if (!uniformWeight)
505
+ return { styles: {} };
506
+ switch (node.strokeAlign) {
507
+ case "OUTSIDE":
508
+ tracker.record(node, "exact", "OUTSIDE stroke rendered via outline (offset 0).");
509
+ return {
510
+ styles: {
511
+ outline: `${px(uniformWeight)} solid ${color}`,
512
+ "outline-offset": "0px",
513
+ },
514
+ };
515
+ case "INSIDE":
516
+ tracker.record(node, "exact", "INSIDE stroke rendered via inset box-shadow.");
517
+ return {
518
+ styles: {},
519
+ insetShadow: `inset 0 0 0 ${px(uniformWeight)} ${color}`,
520
+ };
521
+ case "CENTER":
522
+ default:
523
+ // outline-offset of -half the weight pulls the outline half inside,
524
+ // half outside the border-box edge -- reproducing Figma's CENTER
525
+ // straddle exactly (plain CSS `border` cannot straddle the edge).
526
+ tracker.record(node, "exact", "CENTER stroke rendered via outline with outline-offset = -weight/2 (straddles the edge like Figma).");
527
+ return {
528
+ styles: {
529
+ outline: `${px(uniformWeight)} solid ${color}`,
530
+ "outline-offset": px(-uniformWeight / 2),
531
+ },
532
+ };
533
+ }
534
+ }
535
+ // ---------------------------------------------------------------------------
536
+ // Corner radii
537
+ // ---------------------------------------------------------------------------
538
+ function buildCornerRadius(node) {
539
+ if (node.rectangleCornerRadii) {
540
+ const [tl, tr, br, bl] = node.rectangleCornerRadii;
541
+ return `${px(tl) ?? "0px"} ${px(tr) ?? "0px"} ${px(br) ?? "0px"} ${px(bl) ?? "0px"}`;
542
+ }
543
+ if (typeof node.cornerRadius === "number" && node.cornerRadius > 0) {
544
+ return px(node.cornerRadius);
545
+ }
546
+ return undefined;
547
+ }
548
+ function buildEffects(node, isTextNode, tracker) {
549
+ const effects = (node.effects ?? []).filter((effect) => effect.visible !== false);
550
+ const boxShadowLayers = [];
551
+ let filter;
552
+ let backdropFilter;
553
+ for (const effect of effects) {
554
+ if (effect.type === "DROP_SHADOW" || effect.type === "INNER_SHADOW") {
555
+ const color = colorToCss(effect.color, 1) ?? "rgba(0, 0, 0, 1)";
556
+ const x = px(effect.offset?.x ?? 0) ?? "0px";
557
+ const y = px(effect.offset?.y ?? 0) ?? "0px";
558
+ const blur = px(effect.radius ?? 0) ?? "0px";
559
+ const spread = !isTextNode && typeof effect.spread === "number"
560
+ ? ` ${px(effect.spread)}`
561
+ : "";
562
+ const inset = effect.type === "INNER_SHADOW" ? "inset " : "";
563
+ boxShadowLayers.push(`${inset}${x} ${y} ${blur}${spread} ${color}`);
564
+ tracker.record(node, "exact", `${effect.type} rendered as ${isTextNode ? "text-shadow" : "box-shadow"}.`);
565
+ }
566
+ else if (effect.type === "LAYER_BLUR") {
567
+ const radius = px(effect.radius ?? 0) ?? "0px";
568
+ filter = filter ? `${filter} blur(${radius})` : `blur(${radius})`;
569
+ tracker.record(node, "approximated", "LAYER_BLUR mapped 1:1 to CSS filter: blur(); Figma's blur radius-to-CSS-stdDeviation scale is not publicly documented, so the rendered softness may differ slightly.");
570
+ }
571
+ else if (effect.type === "BACKGROUND_BLUR") {
572
+ const radius = px(effect.radius ?? 0) ?? "0px";
573
+ backdropFilter = backdropFilter
574
+ ? `${backdropFilter} blur(${radius})`
575
+ : `blur(${radius})`;
576
+ tracker.record(node, "approximated", "BACKGROUND_BLUR mapped 1:1 to CSS backdrop-filter: blur(); same radius-scale caveat as LAYER_BLUR.");
577
+ }
578
+ }
579
+ return { boxShadowLayers, filter, backdropFilter };
580
+ }
581
+ // ---------------------------------------------------------------------------
582
+ // Blend modes
583
+ // ---------------------------------------------------------------------------
584
+ const CSS_BLEND_MODES = new Set([
585
+ "multiply",
586
+ "screen",
587
+ "overlay",
588
+ "darken",
589
+ "lighten",
590
+ "color-dodge",
591
+ "color-burn",
592
+ "hard-light",
593
+ "soft-light",
594
+ "difference",
595
+ "exclusion",
596
+ "hue",
597
+ "saturation",
598
+ "color",
599
+ "luminosity",
600
+ ]);
601
+ const FIGMA_ONLY_BLEND_MODE_FALLBACK = {
602
+ LINEAR_BURN: "multiply",
603
+ LINEAR_DODGE: "plus-lighter",
604
+ LIGHTER: "plus-lighter",
605
+ DARKER: "darken",
606
+ };
607
+ function buildBlendMode(node, tracker) {
608
+ const mode = node.blendMode;
609
+ if (!mode || mode === "PASS_THROUGH" || mode === "NORMAL")
610
+ return undefined;
611
+ const cssMode = mode.toLowerCase().replace(/_/g, "-");
612
+ if (CSS_BLEND_MODES.has(cssMode))
613
+ return cssMode;
614
+ const fallback = FIGMA_ONLY_BLEND_MODE_FALLBACK[mode];
615
+ if (fallback) {
616
+ tracker.record(node, "approximated", `Figma blend mode "${mode}" has no CSS equivalent; approximated as mix-blend-mode: ${fallback}.`);
617
+ return fallback;
618
+ }
619
+ return undefined;
620
+ }
621
+ // ---------------------------------------------------------------------------
622
+ // Text styling
623
+ // ---------------------------------------------------------------------------
624
+ function resolveLineHeight(style) {
625
+ if (typeof style.lineHeightPx === "number" &&
626
+ style.lineHeightUnit !== "FONT_SIZE_%") {
627
+ return px(style.lineHeightPx);
628
+ }
629
+ if (typeof style.lineHeightPercentFontSize === "number" &&
630
+ typeof style.fontSize === "number") {
631
+ // lineHeightPercentFontSize is literally "percent of the font's nominal
632
+ // size" -- resolve to an exact px value rather than a unitless ratio so
633
+ // the rendered line box matches Figma regardless of font metrics.
634
+ return px(style.fontSize * (style.lineHeightPercentFontSize / 100));
635
+ }
636
+ if (typeof style.lineHeightPx === "number") {
637
+ return px(style.lineHeightPx);
638
+ }
639
+ return undefined;
640
+ }
641
+ function textTransformCss(textCase) {
642
+ switch (textCase) {
643
+ case "UPPER":
644
+ return "uppercase";
645
+ case "LOWER":
646
+ return "lowercase";
647
+ case "TITLE":
648
+ return "capitalize";
649
+ default:
650
+ return undefined;
651
+ }
652
+ }
653
+ function textDecorationCss(decoration) {
654
+ switch (decoration) {
655
+ case "UNDERLINE":
656
+ return "underline";
657
+ case "STRIKETHROUGH":
658
+ return "line-through";
659
+ default:
660
+ return undefined;
661
+ }
662
+ }
663
+ function textAlignCss(align) {
664
+ switch (align) {
665
+ case "CENTER":
666
+ return "center";
667
+ case "RIGHT":
668
+ return "right";
669
+ case "JUSTIFIED":
670
+ return "justify";
671
+ case "LEFT":
672
+ return "left";
673
+ default:
674
+ return undefined;
675
+ }
676
+ }
677
+ function verticalAlignJustifyContent(align) {
678
+ switch (align) {
679
+ case "CENTER":
680
+ return "center";
681
+ case "BOTTOM":
682
+ return "flex-end";
683
+ default:
684
+ return "flex-start";
685
+ }
686
+ }
687
+ // ---------------------------------------------------------------------------
688
+ // Auto-layout
689
+ // ---------------------------------------------------------------------------
690
+ function primaryAxisJustify(align) {
691
+ switch (align) {
692
+ case "CENTER":
693
+ return "center";
694
+ case "MAX":
695
+ return "flex-end";
696
+ case "SPACE_BETWEEN":
697
+ return "space-between";
698
+ default:
699
+ return "flex-start";
700
+ }
701
+ }
702
+ function counterAxisAlign(align) {
703
+ switch (align) {
704
+ case "CENTER":
705
+ return "center";
706
+ case "MAX":
707
+ return "flex-end";
708
+ case "BASELINE":
709
+ return "baseline";
710
+ default:
711
+ return "flex-start";
712
+ }
713
+ }
714
+ function buildAutoLayoutStyles(node) {
715
+ if (!node.layoutMode ||
716
+ node.layoutMode === "NONE" ||
717
+ node.layoutMode === "GRID") {
718
+ return {};
719
+ }
720
+ const isHorizontal = node.layoutMode === "HORIZONTAL";
721
+ const styles = {
722
+ display: "flex",
723
+ "flex-direction": isHorizontal ? "row" : "column",
724
+ "justify-content": primaryAxisJustify(node.primaryAxisAlignItems),
725
+ "align-items": counterAxisAlign(node.counterAxisAlignItems),
726
+ };
727
+ if (node.layoutWrap === "WRAP")
728
+ styles["flex-wrap"] = "wrap";
729
+ if (typeof node.itemSpacing === "number" && node.itemSpacing !== 0) {
730
+ styles[isHorizontal ? "column-gap" : "row-gap"] = px(node.itemSpacing);
731
+ }
732
+ if (typeof node.counterAxisSpacing === "number" &&
733
+ node.counterAxisSpacing !== 0) {
734
+ styles[isHorizontal ? "row-gap" : "column-gap"] = px(node.counterAxisSpacing);
735
+ }
736
+ const padTop = node.paddingTop ?? 0;
737
+ const padRight = node.paddingRight ?? 0;
738
+ const padBottom = node.paddingBottom ?? 0;
739
+ const padLeft = node.paddingLeft ?? 0;
740
+ if (padTop || padRight || padBottom || padLeft) {
741
+ styles.padding = `${px(padTop)} ${px(padRight)} ${px(padBottom)} ${px(padLeft)}`;
742
+ }
743
+ return styles;
744
+ }
745
+ /**
746
+ * "FILL" sizing must map to different CSS depending on which axis is the
747
+ * flex *main* axis for this node's parent: main-axis FILL grows via
748
+ * `flex-grow`/`flex-basis` (row parent -> horizontal FILL, column parent ->
749
+ * vertical FILL); cross-axis FILL stretches via `align-self: stretch` (row
750
+ * parent -> vertical FILL, column parent -> horizontal FILL). Passing only a
751
+ * `parentHasAutoLayout` boolean (as this used to) loses the row/column
752
+ * direction and always mapped horizontal-FILL to flex-grow — correct for row
753
+ * parents but wrong for column parents, where a FILL-width text/rect child
754
+ * got `width: auto` with no stretch and overflowed to its content width.
755
+ */
756
+ function buildChildSizingStyles(node, parentLayoutMode) {
757
+ if (parentLayoutMode === "NONE")
758
+ return {};
759
+ const parentIsHorizontal = parentLayoutMode === "HORIZONTAL";
760
+ const styles = {};
761
+ if (node.layoutSizingHorizontal === "FILL") {
762
+ if (parentIsHorizontal) {
763
+ styles["flex-grow"] = "1";
764
+ styles["flex-basis"] = "0%";
765
+ }
766
+ else {
767
+ styles["align-self"] = "stretch";
768
+ }
769
+ styles.width = "auto";
770
+ }
771
+ else if (node.layoutSizingHorizontal === "HUG") {
772
+ styles.width = "auto";
773
+ }
774
+ if (node.layoutSizingVertical === "FILL") {
775
+ if (parentIsHorizontal) {
776
+ styles["align-self"] = "stretch";
777
+ }
778
+ else {
779
+ styles["flex-grow"] = "1";
780
+ styles["flex-basis"] = "0%";
781
+ }
782
+ styles.height = "auto";
783
+ }
784
+ else if (node.layoutSizingVertical === "HUG") {
785
+ styles.height = "auto";
786
+ }
787
+ return styles;
788
+ }
789
+ // ---------------------------------------------------------------------------
790
+ // Node type classification
791
+ // ---------------------------------------------------------------------------
792
+ function needsImageFallback(node, options) {
793
+ if (options.forceImageFallbackNodeIds?.has(node.id))
794
+ return true;
795
+ if (UNSUPPORTED_STRUCTURAL_TYPES.has(node.type))
796
+ return true;
797
+ // A Figma mask affects its following siblings, not just the mask node. CSS
798
+ // cannot reproduce that sibling-range operation on an arbitrary DOM tree,
799
+ // so render the smallest containing subtree rather than importing a visibly
800
+ // wrong unmasked composition. A mask imported as the root is also rendered.
801
+ if (node.isMask || node.children?.some((child) => child.isMask))
802
+ return true;
803
+ // A CSS div with an outline is not a Figma line. Partial/ring ellipses also
804
+ // need real path geometry, which this structural mapper intentionally does
805
+ // not request because geometry=paths makes ordinary REST payloads enormous.
806
+ if (node.type === "LINE")
807
+ return true;
808
+ if (node.type === "ELLIPSE" && node.arcData) {
809
+ const start = node.arcData.startingAngle ?? 0;
810
+ const end = node.arcData.endingAngle ?? Math.PI * 2;
811
+ const span = Math.abs(end - start);
812
+ const isFullCircle = Math.abs(span - Math.PI * 2) < 1e-4 &&
813
+ Math.abs(node.arcData.innerRadius ?? 0) < 1e-4;
814
+ if (!isFullCircle)
815
+ return true;
816
+ }
817
+ const visibleStrokes = (node.strokes ?? []).filter((stroke) => stroke.visible !== false);
818
+ if (visibleStrokes.length > 1 ||
819
+ visibleStrokes.some((stroke) => stroke.type !== "SOLID") ||
820
+ (node.strokeDashes?.length ?? 0) > 0) {
821
+ return true;
822
+ }
823
+ const visibleFills = (node.fills ?? []).filter((fill) => fill.visible !== false);
824
+ if (visibleFills.some((fill) => fill.type === "VIDEO" ||
825
+ fill.type === "EMOJI" ||
826
+ (fill.blendMode &&
827
+ fill.blendMode !== "NORMAL" &&
828
+ fill.blendMode !== "PASS_THROUGH") ||
829
+ (fill.type === "IMAGE" &&
830
+ ((fill.imageTransform &&
831
+ (Math.abs(fill.imageTransform[0][1]) >= 1e-6 ||
832
+ Math.abs(fill.imageTransform[1][0]) >= 1e-6)) ||
833
+ Object.values(fill.filters ?? {}).some((value) => typeof value === "number" && Math.abs(value) > 1e-6)))) ||
834
+ (node.type === "TEXT" && visibleFills.some((fill) => fill.type !== "SOLID"))) {
835
+ return true;
836
+ }
837
+ if (node.type === "TEXT") {
838
+ const styles = [
839
+ node.style,
840
+ ...Object.values(node.styleOverrideTable ?? {}),
841
+ ].filter((style) => Boolean(style));
842
+ const hasAdvancedTypography = styles.some((style) => Math.abs(style.paragraphSpacing ?? 0) > 1e-6 ||
843
+ Math.abs(style.paragraphIndent ?? 0) > 1e-6 ||
844
+ Math.abs(style.listSpacing ?? 0) > 1e-6 ||
845
+ style.hangingPunctuation === true ||
846
+ style.hangingList === true ||
847
+ style.hyperlink !== undefined ||
848
+ Object.values(style.opentypeFlags ?? {}).some((value) => value !== 0));
849
+ if (hasAdvancedTypography ||
850
+ // Figma's REST API always returns one `lineTypes` entry per line —
851
+ // ordinary non-list text comes back as `["NONE", "NONE", ...]`, not an
852
+ // empty array. Checking `.length > 0` alone treats every multi-line
853
+ // text node in existence as an unsupported list and routes it to an
854
+ // image fallback; only a line whose type is actually "ORDERED" or
855
+ // "UNORDERED" means the text uses real list formatting.
856
+ (node.lineTypes?.some((type) => type !== "NONE") ?? false) ||
857
+ (node.lineIndentations?.some((value) => value !== 0) ?? false)) {
858
+ return true;
859
+ }
860
+ }
861
+ if ((node.effects ?? []).some((effect) => effect.visible !== false &&
862
+ effect.blendMode &&
863
+ effect.blendMode !== "NORMAL" &&
864
+ effect.blendMode !== "PASS_THROUGH")) {
865
+ return true;
866
+ }
867
+ if (!SUPPORTED_CONTAINER_TYPES.has(node.type) &&
868
+ node.type !== "RECTANGLE" &&
869
+ node.type !== "ELLIPSE" &&
870
+ node.type !== "TEXT") {
871
+ return true;
872
+ }
873
+ return false;
874
+ }
875
+ /** Fail clearly before recursive rendering can overflow or lock the worker. */
876
+ export function assertFigmaNodeTreeComplexity(node) {
877
+ const stack = [{ node, depth: 1 }];
878
+ const ancestors = new WeakSet();
879
+ let count = 0;
880
+ while (stack.length > 0) {
881
+ const current = stack.pop();
882
+ count += 1;
883
+ if (count > MAX_FIGMA_NODE_COUNT) {
884
+ throw new Error(`Figma node tree is too large (max ${MAX_FIGMA_NODE_COUNT.toLocaleString("en-US")} nodes). Import a smaller frame or selection.`);
885
+ }
886
+ if (current.depth > MAX_FIGMA_NODE_DEPTH) {
887
+ throw new Error(`Figma node tree is nested too deeply (max ${MAX_FIGMA_NODE_DEPTH} levels). Import a smaller frame or selection.`);
888
+ }
889
+ if (ancestors.has(current.node)) {
890
+ throw new Error("Figma node tree contains a cyclic child reference.");
891
+ }
892
+ ancestors.add(current.node);
893
+ for (const child of current.node.children ?? []) {
894
+ stack.push({ node: child, depth: current.depth + 1 });
895
+ }
896
+ }
897
+ }
898
+ /**
899
+ * Walk a node tree and return the ids of every subtree that will render as a
900
+ * PNG image fallback (vector networks, boolean ops, and any node type this
901
+ * mapper does not model structurally). Call this before fetching node data
902
+ * so the caller can request rendered images for exactly these ids via
903
+ * `GET /v1/images/:fileKey?ids=...&scale=2`.
904
+ */
905
+ export function collectFallbackNodeIds(node, options = {}) {
906
+ assertFigmaNodeTreeComplexity(node);
907
+ const ids = [];
908
+ const visit = (current) => {
909
+ if (current.visible === false || current.opacity === 0)
910
+ return;
911
+ if (needsImageFallback(current, options)) {
912
+ ids.push(current.id);
913
+ return; // Don't recurse into a subtree that's rendered as one image.
914
+ }
915
+ for (const child of current.children ?? [])
916
+ visit(child);
917
+ };
918
+ visit(node);
919
+ return ids;
920
+ }
921
+ /**
922
+ * Walk a node tree and return every distinct `imageRef` used by IMAGE fills
923
+ * (on fills or strokes) so the caller can resolve them to URLs via
924
+ * `GET /v1/files/:fileKey/images` before mapping.
925
+ */
926
+ export function collectImageFillRefs(node, options = {}) {
927
+ assertFigmaNodeTreeComplexity(node);
928
+ const refs = new Set();
929
+ const visitPaints = (paints) => {
930
+ for (const paint of paints ?? []) {
931
+ if (paint.type === "IMAGE" && paint.imageRef)
932
+ refs.add(paint.imageRef);
933
+ }
934
+ };
935
+ const visit = (current) => {
936
+ if (current.visible === false || current.opacity === 0)
937
+ return;
938
+ if (needsImageFallback(current, options))
939
+ return;
940
+ visitPaints(current.fills);
941
+ visitPaints(current.strokes);
942
+ for (const child of current.children ?? [])
943
+ visit(child);
944
+ };
945
+ visit(node);
946
+ return [...refs];
947
+ }
948
+ function recordFontUsage(style, usage) {
949
+ if (!style?.fontFamily)
950
+ return;
951
+ const weight = typeof style.fontWeight === "number" ? style.fontWeight : 400;
952
+ const italic = Boolean(style.italic);
953
+ const key = `${style.fontFamily}|${weight}|${italic ? 1 : 0}`;
954
+ if (!usage.has(key))
955
+ usage.set(key, { family: style.fontFamily, weight, italic });
956
+ }
957
+ /**
958
+ * Walk a node tree and return every distinct (font family, weight, italic)
959
+ * combination used by TEXT nodes -- including per-run character style
960
+ * overrides -- so the caller can request the actual web font (e.g. from
961
+ * Google Fonts) before the imported HTML is saved. Without this, an imported
962
+ * screen's CSS correctly names the intended font-family, but the browser has
963
+ * no way to load it and silently falls back to a generic sans-serif with
964
+ * different glyph advance widths -- individually invisible per character but
965
+ * compounding into a growing horizontal drift across any wrapped or
966
+ * multi-word line, worst on text-dense imports.
967
+ */
968
+ export function collectFontUsage(node) {
969
+ assertFigmaNodeTreeComplexity(node);
970
+ const usage = new Map();
971
+ const visit = (current) => {
972
+ if (current.visible === false || current.opacity === 0)
973
+ return;
974
+ if (current.type === "TEXT") {
975
+ recordFontUsage(current.style, usage);
976
+ for (const style of Object.values(current.styleOverrideTable ?? {})) {
977
+ recordFontUsage(style, usage);
978
+ }
979
+ }
980
+ for (const child of current.children ?? [])
981
+ visit(child);
982
+ };
983
+ visit(node);
984
+ return [...usage.values()];
985
+ }
986
+ function textOverrideCss(style) {
987
+ const solidFill = [...(style?.fills ?? [])]
988
+ .reverse()
989
+ .find((fill) => fill.visible !== false && fill.type === "SOLID");
990
+ return {
991
+ "font-family": style?.fontFamily
992
+ ? `"${style.fontFamily.replace(/"/g, "")}", sans-serif`
993
+ : undefined,
994
+ "font-size": px(style?.fontSize),
995
+ "font-weight": typeof style?.fontWeight === "number"
996
+ ? String(style.fontWeight)
997
+ : undefined,
998
+ "font-style": style?.italic ? "italic" : undefined,
999
+ "line-height": style ? resolveLineHeight(style) : undefined,
1000
+ "letter-spacing": typeof style?.letterSpacing === "number"
1001
+ ? px(style.letterSpacing)
1002
+ : undefined,
1003
+ "text-transform": textTransformCss(style?.textCase),
1004
+ "text-decoration": textDecorationCss(style?.textDecoration),
1005
+ color: solidFill
1006
+ ? (colorToCss(solidFill.color, solidFill.opacity ?? 1) ?? undefined)
1007
+ : undefined,
1008
+ };
1009
+ }
1010
+ /** Render contiguous Figma character-style override runs as inline spans. */
1011
+ function buildMixedTextHtml(node, characters, tracker) {
1012
+ const overrideIds = node.characterStyleOverrides ?? [];
1013
+ const table = node.styleOverrideTable ?? {};
1014
+ if (characters.length === 0 ||
1015
+ !overrideIds.some((id) => id !== 0 && table[String(id)])) {
1016
+ return escapeHtml(characters);
1017
+ }
1018
+ const runs = [];
1019
+ for (let index = 0; index < characters.length; index += 1) {
1020
+ const id = overrideIds[index] ?? 0;
1021
+ const previous = runs[runs.length - 1];
1022
+ if (previous?.id === id)
1023
+ previous.text += characters[index] ?? "";
1024
+ else
1025
+ runs.push({ id, text: characters[index] ?? "" });
1026
+ }
1027
+ tracker.record(node, "exact", "Mixed character style overrides were preserved as inline text runs.");
1028
+ return runs
1029
+ .map((run) => {
1030
+ if (run.id === 0)
1031
+ return escapeHtml(run.text);
1032
+ const style = table[String(run.id)];
1033
+ if (!style)
1034
+ return escapeHtml(run.text);
1035
+ return `<span style="${styleAttr(textOverrideCss(style))}">${escapeHtml(run.text)}</span>`;
1036
+ })
1037
+ .join("");
1038
+ }
1039
+ // ---------------------------------------------------------------------------
1040
+ // Main mapper
1041
+ // ---------------------------------------------------------------------------
1042
+ function frameRelativeBox(node, parentBox) {
1043
+ const box = node.absoluteBoundingBox;
1044
+ if (!box)
1045
+ return { left: 0, top: 0, width: 0, height: 0 };
1046
+ return {
1047
+ left: box.x - (parentBox?.x ?? box.x),
1048
+ top: box.y - (parentBox?.y ?? box.y),
1049
+ width: box.width,
1050
+ height: box.height,
1051
+ };
1052
+ }
1053
+ /**
1054
+ * Figma's `absoluteBoundingBox` for a rotated node is the axis-aligned
1055
+ * bounding box of the ALREADY-ROTATED shape, not the shape's own (pre-
1056
+ * rotation) width/height -- e.g. a 120x80 rectangle rotated 15 degrees comes
1057
+ * back with an ~136.6x108.3 bounding box. Applying a CSS `rotate()` on TOP
1058
+ * of a div already sized to that expanded AABB rotates an oversized box,
1059
+ * producing a visibly wrong (too-large, wrong-aspect-ratio) rotated shape.
1060
+ * This inverts the AABB formula (`W' = W*|cos| + H*|sin|`,
1061
+ * `H' = W*|sin| + H*|cos|`) to recover the true pre-rotation width/height,
1062
+ * then re-centers the (smaller) box at the same center point the AABB had --
1063
+ * matching this module's existing "rotate about the AABB center" pivot
1064
+ * assumption, so the CSS `rotate()` reproduces the original box exactly.
1065
+ */
1066
+ function unrotateBox(box, rotationDeg) {
1067
+ const theta = (rotationDeg * Math.PI) / 180;
1068
+ const c = Math.abs(Math.cos(theta));
1069
+ const s = Math.abs(Math.sin(theta));
1070
+ const det = c * c - s * s;
1071
+ // Near +-45/+-135 degrees the AABB<->true-size system is near-singular
1072
+ // (many different true sizes produce almost the same AABB); fall back to
1073
+ // the AABB dimensions rather than dividing by ~zero and producing a huge
1074
+ // or negative "true" size.
1075
+ if (Math.abs(det) < 0.05)
1076
+ return box;
1077
+ const trueWidth = (c * box.width - s * box.height) / det;
1078
+ const trueHeight = (c * box.height - s * box.width) / det;
1079
+ if (!Number.isFinite(trueWidth) ||
1080
+ !Number.isFinite(trueHeight) ||
1081
+ trueWidth <= 0 ||
1082
+ trueHeight <= 0) {
1083
+ return box;
1084
+ }
1085
+ const centerX = box.left + box.width / 2;
1086
+ const centerY = box.top + box.height / 2;
1087
+ return {
1088
+ left: centerX - trueWidth / 2,
1089
+ top: centerY - trueHeight / 2,
1090
+ width: trueWidth,
1091
+ height: trueHeight,
1092
+ };
1093
+ }
1094
+ /**
1095
+ * Same as `frameRelativeBox` but sized/positioned from `absoluteRenderBounds`
1096
+ * (falling back to `absoluteBoundingBox` when Figma didn't return render
1097
+ * bounds). Used only for image-fallback `<img>` geometry -- see the
1098
+ * `absoluteRenderBounds` field doc for why the geometric box is wrong there.
1099
+ */
1100
+ function frameRelativeRenderBox(node, parentBox) {
1101
+ const box = node.absoluteRenderBounds ?? node.absoluteBoundingBox;
1102
+ if (!box)
1103
+ return { left: 0, top: 0, width: 0, height: 0 };
1104
+ return {
1105
+ left: box.x - (parentBox?.x ?? box.x),
1106
+ top: box.y - (parentBox?.y ?? box.y),
1107
+ width: box.width,
1108
+ height: box.height,
1109
+ };
1110
+ }
1111
+ function buildNode(node, parentBox, parentLayoutMode, options, tracker, isRoot) {
1112
+ const parentHasAutoLayout = parentLayoutMode !== "NONE";
1113
+ if (node.visible === false || node.opacity === 0)
1114
+ return "";
1115
+ let box = frameRelativeBox(node, parentBox);
1116
+ // The Figma REST API's file-node-types docs describe `rotation` as
1117
+ // "in degrees", but empirically (verified against known authored values
1118
+ // via the Plugin API -- e.g. an authored 15deg/20deg rotation comes back
1119
+ // as 0.2617993.../0.3490658... here) the REST API actually returns
1120
+ // RADIANS. Treating that value as degrees silently shrinks every rotation
1121
+ // by a factor of ~57 (pi/180), rendering rotated content as visually
1122
+ // unrotated. Convert to degrees before using it anywhere below.
1123
+ const rotationDeg = typeof node.rotation === "number"
1124
+ ? (node.rotation * 180) / Math.PI
1125
+ : undefined;
1126
+ const rotation = rotationDeg !== undefined && Math.abs(rotationDeg) > 0.001
1127
+ ? rotationDeg
1128
+ : undefined;
1129
+ if (rotation !== undefined) {
1130
+ // `box` (from absoluteBoundingBox) is the rotated shape's AABB; recover
1131
+ // the true pre-rotation width/height/position so fills/effects/strokes
1132
+ // below -- and the CSS `rotate()` applied later -- operate on the
1133
+ // correct box instead of an oversized one. See `unrotateBox`.
1134
+ box = unrotateBox(box, rotation);
1135
+ }
1136
+ const nameAttr = node.name
1137
+ ? ` data-agent-native-layer-name="${escapeAttr(node.name)}"`
1138
+ : "";
1139
+ const idAttr = ` data-figma-node-id="${escapeAttr(node.id)}"`;
1140
+ const typeAttr = ` data-figma-node-type="${escapeAttr(node.type)}"`;
1141
+ const semanticAttrs = metadataAttr("data-figma-component-id", node.componentId, node, tracker) +
1142
+ metadataAttr("data-figma-component-properties", node.componentProperties, node, tracker) +
1143
+ metadataAttr("data-figma-bound-variables", node.boundVariables, node, tracker) +
1144
+ metadataAttr("data-figma-interactions", node.interactions, node, tracker);
1145
+ if (node.componentId || node.componentProperties) {
1146
+ tracker.record(node, "approximated", "Figma component/instance provenance was preserved as metadata, but the imported HTML is not linked to the original Figma component master.");
1147
+ }
1148
+ if (node.boundVariables && Object.keys(node.boundVariables).length > 0) {
1149
+ tracker.record(node, "approximated", "Figma variable bindings were preserved as metadata; resolved visual values are imported, but bindings are not live Design tokens.");
1150
+ }
1151
+ if (node.interactions && node.interactions.length > 0) {
1152
+ tracker.record(node, "approximated", "Prototype interactions were preserved as inert metadata and do not execute or navigate inside the editor preview.");
1153
+ }
1154
+ if (needsImageFallback(node, options)) {
1155
+ const imageUrl = options.fallbackImageUrls?.[node.id];
1156
+ if (!imageUrl) {
1157
+ tracker.record(node, "image-fallback", `Node type "${node.type}" requires an image fallback but no rendered URL was provided; nothing was rendered for this node.`);
1158
+ return "";
1159
+ }
1160
+ tracker.record(node, "image-fallback", `Node type "${node.type}" cannot be reproduced structurally (vector network / boolean op / unsupported type); rendered as an exact PNG (scale=2) instead of an approximated structural guess.`);
1161
+ const isFlowChild = !isRoot && parentHasAutoLayout && node.layoutPositioning !== "ABSOLUTE";
1162
+ // Use render bounds (not the geometric box) so a fallback PNG whose
1163
+ // stroke/effects overflow the node's own bounding box (e.g. an
1164
+ // OUTSIDE-aligned stroke) is placed at its natural size instead of being
1165
+ // squished/cropped into the smaller geometric box.
1166
+ const renderBox = frameRelativeRenderBox(node, parentBox);
1167
+ const styles = {
1168
+ position: isRoot || isFlowChild ? "relative" : "absolute",
1169
+ left: isRoot || isFlowChild ? undefined : px(renderBox.left),
1170
+ top: isRoot || isFlowChild ? undefined : px(renderBox.top),
1171
+ width: px(renderBox.width),
1172
+ height: px(renderBox.height),
1173
+ opacity: typeof node.opacity === "number" && node.opacity !== 1
1174
+ ? String(round(node.opacity, 4))
1175
+ : undefined,
1176
+ };
1177
+ return `<img${idAttr}${typeAttr}${nameAttr}${semanticAttrs} src="${escapeAttr(imageUrl)}" alt="${escapeAttr(node.name ?? "")}" style="${styleAttr(styles)}" />`;
1178
+ }
1179
+ const isTextNode = node.type === "TEXT";
1180
+ const isEllipse = node.type === "ELLIPSE";
1181
+ const box2 = { width: box.width, height: box.height };
1182
+ const fills = buildFills(node, node.fills, box2, options, tracker, isTextNode);
1183
+ const strokeResult = buildStrokes(node, tracker);
1184
+ const effects = buildEffects(node, isTextNode, tracker);
1185
+ const cornerRadius = isEllipse ? "50%" : buildCornerRadius(node);
1186
+ const blendMode = buildBlendMode(node, tracker);
1187
+ const boxShadowParts = [...effects.boxShadowLayers];
1188
+ if (strokeResult.insetShadow)
1189
+ boxShadowParts.push(strokeResult.insetShadow);
1190
+ if (rotation !== undefined) {
1191
+ tracker.record(node, "approximated", `Rotation (${round(rotation, 2)}deg) reconstructed by pivoting the unrotated box about the absoluteBoundingBox center; exact only when Figma's internal pivot is also the shape's center.`);
1192
+ }
1193
+ const autoLayoutStyles = buildAutoLayoutStyles(node);
1194
+ const childSizingStyles = buildChildSizingStyles(node, parentLayoutMode);
1195
+ const hasAutoLayout = Boolean(autoLayoutStyles.display);
1196
+ // A node is positioned relative to its parent's free canvas (absolute,
1197
+ // left/top from absoluteBoundingBox) unless its *parent* is an auto-layout
1198
+ // container, in which case it's a normal flex item (relative, no left/top)
1199
+ // -- this mirrors Figma's own rule that auto-layout children give up
1200
+ // manual x/y in favor of flex flow.
1201
+ const isFlexChild = !isRoot && parentHasAutoLayout && node.layoutPositioning !== "ABSOLUTE";
1202
+ const baseStyles = {
1203
+ position: isRoot ? "relative" : isFlexChild ? "relative" : "absolute",
1204
+ left: isRoot || isFlexChild ? undefined : px(box.left),
1205
+ top: isRoot || isFlexChild ? undefined : px(box.top),
1206
+ width: childSizingStyles.width ?? px(box.width),
1207
+ height: childSizingStyles.height ?? px(box.height),
1208
+ "background-color": fills.backgroundColor,
1209
+ "background-image": fills.backgroundImage,
1210
+ "background-size": fills.backgroundSize,
1211
+ "background-position": fills.backgroundPosition,
1212
+ "background-repeat": fills.backgroundRepeat,
1213
+ color: fills.color,
1214
+ "border-radius": cornerRadius,
1215
+ "box-shadow": boxShadowParts.length > 0 ? boxShadowParts.join(", ") : undefined,
1216
+ filter: effects.filter,
1217
+ "backdrop-filter": effects.backdropFilter,
1218
+ "-webkit-backdrop-filter": effects.backdropFilter,
1219
+ opacity: typeof node.opacity === "number" && node.opacity !== 1
1220
+ ? String(round(node.opacity, 4))
1221
+ : undefined,
1222
+ "mix-blend-mode": blendMode,
1223
+ overflow: node.clipsContent ? "hidden" : undefined,
1224
+ transform: rotation !== undefined ? `rotate(${round(-rotation, 3)}deg)` : undefined,
1225
+ "transform-origin": rotation !== undefined ? "center" : undefined,
1226
+ "min-width": px(node.minWidth ?? undefined),
1227
+ "max-width": px(node.maxWidth ?? undefined),
1228
+ "min-height": px(node.minHeight ?? undefined),
1229
+ "max-height": px(node.maxHeight ?? undefined),
1230
+ ...autoLayoutStyles,
1231
+ ...strokeResult.styles,
1232
+ ...childSizingStyles,
1233
+ };
1234
+ if (isTextNode) {
1235
+ const style = node.style ?? {};
1236
+ baseStyles["font-family"] = style.fontFamily
1237
+ ? `"${style.fontFamily.replace(/"/g, "")}", sans-serif`
1238
+ : undefined;
1239
+ baseStyles["font-size"] = px(style.fontSize);
1240
+ baseStyles["font-weight"] =
1241
+ typeof style.fontWeight === "number"
1242
+ ? String(style.fontWeight)
1243
+ : undefined;
1244
+ baseStyles["font-style"] = style.italic ? "italic" : undefined;
1245
+ baseStyles["line-height"] = resolveLineHeight(style);
1246
+ baseStyles["letter-spacing"] =
1247
+ typeof style.letterSpacing === "number" && style.letterSpacing !== 0
1248
+ ? px(style.letterSpacing)
1249
+ : undefined;
1250
+ baseStyles["text-transform"] = textTransformCss(style.textCase);
1251
+ baseStyles["text-decoration"] = textDecorationCss(style.textDecoration);
1252
+ baseStyles["text-align"] = textAlignCss(style.textAlignHorizontal);
1253
+ if (style.textAutoResize === "TRUNCATE") {
1254
+ baseStyles["white-space"] = "nowrap";
1255
+ baseStyles.overflow = "hidden";
1256
+ baseStyles["text-overflow"] = "ellipsis";
1257
+ }
1258
+ else {
1259
+ // Figma preserves explicit newlines and repeated spaces. Normal HTML
1260
+ // whitespace collapsing changes both wrapping and measured geometry.
1261
+ baseStyles["white-space"] = "pre-wrap";
1262
+ }
1263
+ baseStyles.display = "flex";
1264
+ baseStyles["flex-direction"] = "column";
1265
+ baseStyles["justify-content"] = verticalAlignJustifyContent(style.textAlignVertical);
1266
+ tracker.record(node, "exact", "Text styling mapped from TypeStyle fields.");
1267
+ const characters = node.characters ?? "";
1268
+ const textHtml = buildMixedTextHtml(node, characters, tracker);
1269
+ return `<div${idAttr}${typeAttr}${nameAttr}${semanticAttrs} style="${styleAttr(baseStyles)}"><span>${textHtml}</span></div>`;
1270
+ }
1271
+ tracker.record(node, "exact", "Position, size, fills, strokes, and effects mapped 1:1.");
1272
+ // hasAutoLayout guarantees node.layoutMode is "HORIZONTAL" or "VERTICAL"
1273
+ // (buildAutoLayoutStyles returns {} -- no `display` -- for "NONE"/"GRID").
1274
+ const childParentLayoutMode = hasAutoLayout ? node.layoutMode : "NONE";
1275
+ const childrenHtml = (node.children ?? [])
1276
+ .map((child) => buildNode(child, node.absoluteBoundingBox ?? null, childParentLayoutMode, options, tracker, false))
1277
+ .filter(Boolean)
1278
+ .join("\n");
1279
+ return `<div${idAttr}${typeAttr}${nameAttr}${semanticAttrs} style="${styleAttr(baseStyles)}">\n${childrenHtml}\n</div>`;
1280
+ }
1281
+ /**
1282
+ * Map a Figma node (and its subtree) to an HTML fragment plus a fidelity
1283
+ * report describing which properties were exact, approximated, or rendered
1284
+ * as an image fallback.
1285
+ */
1286
+ export function mapFigmaNodeToHtml(node, options = {}) {
1287
+ assertFigmaNodeTreeComplexity(node);
1288
+ const tracker = new FidelityTracker();
1289
+ const html = buildNode(node, null, "NONE", options, tracker, true);
1290
+ return { html, fidelity: tracker.build() };
1291
+ }
1292
+ //# sourceMappingURL=figma-node-to-html.js.map