@superblocksteam/library 2.0.70-next.2 → 2.0.70-next.4

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.
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["Component","propertiesDefinition","defaultEditorConfig: EditorConfig","chainableComponent: Chainable<React.ComponentProps<T>>","catalog: Catalog","cachedRootFontSize: number | undefined","variables: ExtractedVariables","cachedSizePresets: {\n height: ThemeToken[];\n width: ThemeToken[];\n spacing: ThemeToken[];\n} | null","sizePresets: ThemeToken[]","cachedBorderPresets: {\n borderWidth: ThemeToken[];\n borderRadius: ThemeToken[];\n boxShadow: ThemeToken[];\n} | null","sizePresets: ThemeToken[]","boxShadowPresets: ThemeToken[]","cachedColorPresets: ThemeToken[] | null","propertiesDefinition","TYPOGRAPHY_PRIORITIZED_PROPERTIES: TailwindPropertyKey[]","CONTAINER_PRIORITIZED_PROPERTIES: TailwindPropertyKey[]","sections: PropertiesPanelDefinition<React.ComponentProps<any>>","handleBootstrapResponse: IframeEventHandler<\n \"sb-bootstrap-response\"\n>","rootStore","rootStore","BuildErrorNotification","buildError: BuildError","rootStore","properties: Record<string, PropertyInfo>","rootStore","context: CreationContext","context","editorTemplateCreateRequest","baseProperties","otherComponentsUpdates","runtimeTrackingStore: RuntimeTrackingStore","serverUrl: string","timeoutId: ReturnType<typeof setTimeout> | undefined","stopSocketHeartbeat: (() => void) | undefined","action","payload: ReparentRequest","payload: DeleteRequest","operation","asSetProperties: SetPropertiesRequest","payload: SetPropertiesRequest","SourceUpdateApi","editStore: EditStore","componentsManager: ComponentRegistry","propertiesDefinition","editStore: EditStore | undefined","sourceNode: SourceCodeNode","current: SbSelector | undefined","registeredMatches: SbSelector[]","root: RootStore","properties: Record<string, PropertyInfo<unknown>>","Property","root: RootStore","editStore: EditStore","selectorId","component: RuntimeComponentData","path: PathNode[]","current: SbSelector | undefined","children: SubtreeNode[]","editStore: EditStore","out: Record<SbElement, RuntimeSyncComposite | null>","UIStore","OperationManager","PropertiesPanelManager","RuntimeTrackingStore","ConnectionManager","rootStore","useHotkeysOriginal","NamePill: ReturnType<typeof observer<NamePillProps>>","NamePill","transforms: Array<{ computed: string; element: HTMLElement }>","current: HTMLElement | null","data: TransformData","data","values","width","height","components: { selectorId: SbSelector; sourceId: SbElement }[]","selectedRects: SelectionInfo[]","handleCaptureScreenshot: IframeEventHandler<\n \"capture-screenshot\"\n >","_setReloadKey: (fn: (currentKey: number) => number) => void","handleInit: IframeEventHandler<\"sb-init\">","sourceUpdateApi","handleTokenUpdate: IframeEventHandler<\"sb-update-token\">","IframeConnected","handleDragStart: IframeEventHandler<\"dragstart\">","pendingLogs: Array<{\n level: \"log\" | \"warn\" | \"error\" | \"info\" | \"debug\";\n args: any[];\n stack?: string;\n }>","flushTimer: NodeJS.Timeout | null","stack: string | undefined","rootStore","WithUserWrapper","timeout: NodeJS.Timeout","bootstrapResponseListener: IframeEventHandler<\n \"sb-bootstrap-response\"\n >","updateActiveAgentsListener: IframeEventHandler<\n \"sb-update-active-agents\"\n >","retrievePropertyPanelPropsListener: IframeEventHandler<\n \"sb-retrieve-property-panel-props\"\n >","editOperationAcknowledgeListener: IframeEventHandler<\n \"sb-edit-operation-acknowledge\"\n >","updatePropertyWithEffectsListener: IframeEventHandler<\n \"sb-update-property-with-effects\"\n >","createComponentListener: IframeEventHandler<\n \"sb-create-component\"\n >","error","setInteractionModeListener: IframeEventHandler<\n \"set-interaction-mode\"\n >","globalSyncListener: IframeEventHandler<\"sb-global-sync\">","navigateToListener: IframeEventHandler<\"route-change\">","aiUpdatesListener: IframeEventHandler<\"ai-updates\">","hmrReloadListener: IframeEventHandler<\"hmr-reload-request\">","action","sourceIds: SbElement[]","throttle","timeoutId: ReturnType<typeof setTimeout>","modifiedElements: Array<{\n element: HTMLElement;\n hadInlineStyle: boolean;\n originalValue: string;\n }>","hoveredPills: { selectorId: SbSelector; noSelect?: boolean }[]","hoveredActual: { selectorId: SbSelector; noSelect?: boolean }[]","actualSelectorId: SbSelector | undefined","rootStore","current: HTMLElement | null","throttle","observer","rootStore","Auth0Wrapper","EmbedWrapper","timeout: NodeJS.Timeout","rootStore","bootstrapResponseListener: IframeEventHandler<\n \"sb-bootstrap-response\"\n >","globalSyncListener: IframeEventHandler<\"sb-global-sync\">","navigateToListener: IframeEventHandler<\"route-change\">","action","rootStore","rootStore","VARIABLES: Record<string, string>","VARIABLE_VALUES: Record<keyof typeof VARIABLES, string>","componentVariables: Record<string, string>","componentVariableValues: Record<string, string>","registry: Record<string, string>","loadApisIntoLibrary","Auth0Wrapper","EditorAuth0Wrapper","AppAuth0Wrapper","EmbedWrapper","EditorEmbedWrapper","AppEmbedWrapper","SbProvider","resolvePromiseListener: IframeEventHandler<\"resolve-promise\">","rejectPromiseListener: IframeEventHandler<\"reject-promise\">","context","InteractionLayer","editorConfig: EditorConfig","SuperblocksProvider","context","ErrorMessage","colors","GeneralErrorImage","AppNotFoundImage","ServerError500Image","ForbiddenErrorImage","LoginErrorImage","ErrorComponent","LibraryEarlyConsoleBuffer"],"sources":["../../src/lib/internal-details/sb-wrapper.tsx","../../src/lib/user-facing/properties-panel/mixins/inline-styles-category.ts","../../src/lib/user-facing/properties-panel/mixins/convert-rem-to-pixels.ts","../../src/lib/user-facing/properties-panel/mixins/extract-variables.ts","../../src/lib/user-facing/properties-panel/mixins/style-tokens-size.ts","../../src/lib/user-facing/properties-panel/mixins/style-tokens-border.ts","../../src/lib/user-facing/properties-panel/mixins/style-tokens-color.ts","../../src/lib/user-facing/properties-panel/mixins/styles-category.ts","../../src/lib/user-facing/components/custom/register-custom-component.tsx","../../src/lib/user-facing/components/html/html-property-panels.ts","../../src/lib/user-facing/components/html/register-html-elements.ts","../../src/lib/internal-details/handle-bootstrap-response.ts","../../src/lib/internal-details/internal-components/spinner.tsx","../../src/lib/internal-details/lib/features/injected-features.ts","../../src/lib/internal-details/use-api.ts","../../src/edit-mode/build-error-notification.tsx","../../src/edit-mode/create-component.ts","../../src/edit-mode/features/ai-store.ts","../../src/edit-mode/features/connection-manager.ts","../../src/edit-mode/async-socket.ts","../../src/edit-mode/source-update-api.ts","../../src/edit-mode/features/operation-store.ts","../../src/edit-mode/features/properties-panel-manager.ts","../../src/edit-mode/runtime-graph/observable-graph.ts","../../src/edit-mode/runtime-graph/runtime-component-node.ts","../../src/edit-mode/features/runtime-tracking-store.ts","../../src/edit-mode/features/resizing-store.ts","../../src/edit-mode/features/ui-store.ts","../../src/edit-mode/runtime-sync/builders.ts","../../src/edit-mode/runtime-sync/runtime-subscriptions-store.ts","../../src/edit-mode/edit-store.ts","../../src/lib/hooks/use-editor-hotkeys.ts","../../src/lib/hooks/use-key-pressed.ts","../../src/lib/hooks/use-observer-memo.ts","../../src/lib/user-facing/layers.ts","../../src/edit-mode/interaction-utils.ts","../../src/edit-mode/interaction-layer/interaction-rect-name-pill.tsx","../../src/edit-mode/interaction-layer/interaction-rect-actions.tsx","../../src/edit-mode/interaction-layer/transform-utils.ts","../../src/edit-mode/interaction-layer/interaction-rect.tsx","../../src/edit-mode/editor-hotkeys.tsx","../../src/edit-mode/screenshot-handler.ts","../../src/edit-mode/iframe-wrappers.tsx","../../src/lib/internal-details/lib/throttle.ts","../../src/edit-mode/extended-clickable-area.ts","../../src/edit-mode/interaction-layer/get-widgets-from-point.ts","../../src/edit-mode/interaction-layer/interaction-layer.tsx","../../src/lib/internal-details/app-wrappers.tsx","../../src/lib/internal-details/internal-components/error-boundary/index.tsx","../../src/lib/internal-details/lib/devtools/index.tsx","../../src/lib/internal-details/routing.ts","../../src/lib/user-facing/sb-provider-tracker.ts","../../src/lib/user-facing/styling/styles.ts","../../src/lib/user-facing/sb-provider.tsx","../../src/lib/user-facing/components/app/editor.ts","../../src/lib/user-facing/components/app/props.ts","../../src/lib/user-facing/components/app/index.tsx","../../src/lib/user-facing/error-pages/constants.ts","../../src/lib/user-facing/assets/images/errors/403-image.svg","../../src/lib/user-facing/assets/images/errors/404-image.svg","../../src/lib/user-facing/assets/images/errors/500-image.svg","../../src/lib/user-facing/assets/images/errors/general-error.svg","../../src/lib/user-facing/assets/images/errors/login-error.svg","../../src/lib/user-facing/error-pages/error-component.tsx","../../src/lib/user-facing/error-pages/page-not-found.tsx","../../src/lib/internal-details/internal-components/route-load-error.tsx","../../src/lib/index.ts"],"sourcesContent":["import { getEditStore } from \"../../edit-mode/get-edit-store.js\";\nimport {\n createManagedPropsList,\n createInternalPropsList,\n} from \"../user-facing/properties-panel/create-managed-props-list.js\";\nimport rootStore from \"./lib/root-store.js\";\nimport type { DefaultTagNames } from \"./lib/features/component-registry.js\";\nimport type {\n ExternalProps,\n PropertiesDefinition,\n RawPropsToExternal,\n} from \"../user-facing/properties-panel/props-builder.js\";\nimport type { DataTypeString } from \"@superblocksteam/library-shared/props\";\nimport type {\n AnonymousSbEntity,\n CreateChild,\n PropertyInfo,\n Catalog,\n EditorConfig,\n} from \"@superblocksteam/library-shared/types\";\nimport type React from \"react\";\nimport type { LegacyRef } from \"react\";\n\nexport type InjectedProps = {\n dropTargetRef?: React.Ref<HTMLElement> | LegacyRef<HTMLElement>;\n};\n\nexport type ParentInfo = {\n type?: string;\n};\n\nexport interface CreationContext {\n parentInfo: ParentInfo;\n defaultTagNames: DefaultTagNames;\n selfTagName: string;\n generateUniqueName: (prefix: string) => string;\n}\n\nexport type PropertyValues<P extends React.ComponentProps<any>> = {\n [K in keyof P]?: PropertyInfo | PropertyValues<P[K]>;\n};\n\nexport interface EditorTemplate<\n P extends React.ComponentProps<any> = React.ComponentProps<any>,\n> {\n catalog?: Catalog;\n /***\n * Config for the newly created component when added to the canvas from the Editor.\n * @returns a single CreateRequest or an array of CreateRequests.\n *\n * When returning Array<CreateRequests>:\n * - The 1st CreateRequest's type must match the componentType passed to createComponent.\n * - The last CreateRequest's will be the selected component after drag & drop.\n *\n * Example: [Modal, Button]\n * A modal that when drag & dropped on the page will add a trigger button.\n * The modal is closed by default, so the selected component after drop will be the trigger button.\n */\n create?: (\n context: CreationContext,\n ) => CreateRequest<P> | Array<CreateRequest<P>>;\n}\nexport interface CreateRequest<\n P extends React.ComponentProps<any> = React.ComponentProps<any>,\n> {\n type: string;\n properties?: PropertyValues<P>;\n createAt?: \"root\" | \"dropLocation\"; // default is \"dropLocation\"\n children?: CreateChild[];\n}\n\n// Chainable component interface\nexport interface Chainable<\n PROPS extends React.ComponentProps<any> = React.ComponentProps<any>,\n> {\n addEditorTemplate: (config: EditorTemplate<PROPS>) => Chainable<PROPS>;\n editorConfig: (config: EditorConfig) => Chainable<PROPS>;\n}\n\n/**\n * Register a component to be used with the framework.\n *\n * @param Component - The React component or HTML element name (e.g., \"div\") to register. Can be a React functional component, class component, or intrinsic element string.\n * @param propertiesDefinition - The definition of the component's properties, used for property panel generation and validation.\n *\n * @returns A chainable object that provides methods for editor integration (addEditorTemplate and editorConfig).\n */\nexport const registerComponentInternal = <T extends React.ElementType>(\n Component: T,\n propertiesDefinition: PropertiesDefinition,\n): Chainable<React.ComponentProps<T>> => {\n const type =\n typeof Component === \"string\"\n ? Component\n : Component.displayName || Component.name;\n\n if (!type) {\n throw new Error(\n `Component must have a name or displayName property, or be a string. Received: ${Component}`,\n );\n }\n\n const managedProps = createManagedPropsList(propertiesDefinition);\n\n // Syntactic sugar to set isDroppable to true when the component has children\n const isDroppable = !!managedProps.find(\n (p) => p.path === \"children\" && p.dataType === (\"jsx\" as DataTypeString),\n );\n\n rootStore.onEditorRegistered(() => {\n getEditStore().propertiesPanelManager.setPropertiesDefinition(\n type,\n propertiesDefinition,\n );\n });\n\n rootStore.componentRegistry.addComponent(\n type,\n Component,\n propertiesDefinition,\n );\n rootStore.componentRegistry.addManagedProps(type, managedProps ?? []);\n\n const defaultEditorConfig: EditorConfig = {};\n\n // TODO: This is only necessary on edit-mode\n if (isDroppable) {\n defaultEditorConfig.isDroppable = true;\n rootStore.componentRegistry.addEditorConfig(type, defaultEditorConfig);\n }\n\n // Return chainable object for editor configuration\n const chainableComponent: Chainable<React.ComponentProps<T>> = {\n addEditorTemplate: (\n templateConfig: EditorTemplate<React.ComponentProps<T>>,\n ): Chainable<React.ComponentProps<T>> => {\n const catalog: Catalog = templateConfig.catalog ?? {\n displayName: type,\n category: \"MISC\",\n };\n rootStore.componentRegistry.addEditorTemplate(type, {\n ...templateConfig,\n catalog,\n });\n return chainableComponent;\n },\n editorConfig: (\n config: EditorConfig,\n ): Chainable<React.ComponentProps<T>> => {\n rootStore.componentRegistry.addEditorConfig(type, {\n ...defaultEditorConfig,\n ...config,\n });\n return chainableComponent;\n },\n };\n\n return chainableComponent;\n};\n\nexport function registerEntity<\n PROPS,\n PD extends PropertiesDefinition,\n EP extends ExternalProps<PD> = ExternalProps<PD>,\n>(\n name: string,\n config: { propertiesDefinition: PD },\n Entity: (args: RawPropsToExternal<PROPS>) => EP & AnonymousSbEntity,\n): (args: RawPropsToExternal<PROPS>) => EP & AnonymousSbEntity {\n const managedProps = createManagedPropsList(config.propertiesDefinition);\n const internalProps = createInternalPropsList(config.propertiesDefinition);\n\n rootStore.componentRegistry.addManagedProps(name, managedProps ?? []);\n rootStore.componentRegistry.addInternalProps(name, internalProps ?? []);\n\n rootStore.onEditorRegistered(() => {\n getEditStore().propertiesPanelManager.setPropertiesDefinition(\n name,\n config.propertiesDefinition,\n );\n });\n\n return Entity;\n}\n","import { Prop, PropsCategory, Section } from \"../props-builder.js\";\n\n/**\n * Creates a standardized inline styles section for use in properties panels.\n * This provides a consistent interface for applying inline CSS styles across components.\n *\n * @param options - Configuration options to override defaults\n * @returns A Section with PropsCategory.Styles containing a style prop\n */\nexport const inlineStylesCategory = (\n options: Parameters<ReturnType<typeof Prop.any>[\"propertiesPanel\"]>[0] = {},\n): Section<{ style: React.CSSProperties }> => {\n const styleProp = Prop.any().propertiesPanel({\n label: \"Inline Styles\",\n controlType: \"INLINE_STYLE_BUILDER\" as const,\n description: \"Custom inline CSS styles\",\n isRemovable: true,\n defaultOnAdd: {},\n collapsibleHeader: true,\n ...options,\n });\n\n // Hide this property if there are no styles\n const originalToDefinition = styleProp.toDefinition.bind(styleProp);\n styleProp.toDefinition = function (props: Record<string, unknown>) {\n const styleValue = props?.style;\n\n if (\n !styleValue ||\n (typeof styleValue === \"string\" && styleValue.trim() === \"\") ||\n (typeof styleValue === \"object\" &&\n !Array.isArray(styleValue) &&\n Object.keys(styleValue).length === 0)\n ) {\n return undefined;\n }\n\n return originalToDefinition(props);\n };\n\n return Section.category(PropsCategory.Styles)\n .children({\n style: styleProp,\n })\n .propertiesPanel({\n showHeader: false,\n });\n};\n","let cachedRootFontSize: number | undefined = undefined;\nconst getRootFontSize = () => {\n // Memoized value\n if (cachedRootFontSize !== undefined) {\n return cachedRootFontSize;\n }\n\n if (typeof window !== \"undefined\" && typeof document !== \"undefined\") {\n try {\n const rootFontSize = window.getComputedStyle(\n document.documentElement,\n ).fontSize;\n const parsed = parseFloat(rootFontSize);\n if (!isNaN(parsed) && parsed > 0) {\n // Only cache if we successfully parsed a valid number\n cachedRootFontSize = parsed;\n return cachedRootFontSize;\n }\n } catch {\n console.error(\"Error getting root font size, using fallback of 16px\");\n }\n }\n return 16; // Fallback to default\n};\n\n/**\n * Converts CSS values with rem units to pixel values.\n * Uses the actual computed root font size from the browser.\n *\n * @param value - CSS value (e.g., \"1rem\", \"16px\", \"0.25rem\")\n * @returns Converted value in pixels if input was in rem, otherwise returns original value\n *\n * @example\n * convertRemToPixels(\"1rem\") // \"16px\" (assuming default root font size)\n * convertRemToPixels(\"0.5rem\") // \"8px\"\n * convertRemToPixels(\"16px\") // \"16px\" (unchanged)\n * convertRemToPixels(\"100%\") // \"100%\" (unchanged)\n */\nexport function convertRemToPixels(value: string): string {\n const remMatch = value.match(/^([\\d.]+)rem$/);\n if (!remMatch) {\n return value;\n }\n\n const remValue = parseFloat(remMatch[1]);\n const rootFontSize = getRootFontSize();\n const pixelValue = remValue * rootFontSize;\n\n // Round to avoid floating point precision issues for common values\n // e.g., 0.25 * 16 = 4.0 instead of 3.9999999\n const rounded =\n Math.abs(pixelValue - Math.round(pixelValue)) < 0.0001\n ? Math.round(pixelValue)\n : pixelValue;\n\n return `${rounded}px`;\n}\n","import postcss from \"postcss\";\n\ninterface ExtractedVariables {\n root: Record<string, string>;\n dark: Record<string, string>;\n theme: Record<string, string>;\n}\n\nasync function extractCSSVariablesFromContent(\n cssContent: string,\n): Promise<ExtractedVariables> {\n const variables: ExtractedVariables = {\n root: {},\n dark: {},\n theme: {},\n };\n\n try {\n const extractVariablesPlugin = () => {\n return {\n postcssPlugin: \"extract-variables\",\n Once(root: postcss.Root) {\n root.walkRules((rule) => {\n if (rule.selector === \":root\") {\n rule.walkDecls((decl) => {\n if (decl.prop.startsWith(\"--\")) {\n variables.root[decl.prop] = decl.value;\n }\n });\n } else if (rule.selector === \".dark\") {\n rule.walkDecls((decl) => {\n if (decl.prop.startsWith(\"--\")) {\n variables.dark[decl.prop] = decl.value;\n }\n });\n }\n });\n\n // Extract from @theme inline\n root.walkAtRules(\"theme\", (atRule) => {\n if (atRule.params === \"inline\") {\n atRule.walkDecls((decl) => {\n if (decl.prop.startsWith(\"--\")) {\n variables.theme[decl.prop] = decl.value;\n }\n });\n }\n });\n },\n };\n };\n\n extractVariablesPlugin.postcssPlugin = \"extract-variables\";\n\n await postcss([extractVariablesPlugin()]).process(cssContent, {\n from: undefined,\n });\n\n return variables;\n } catch (error) {\n throw new Error(\n `Failed to extract CSS variables: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n}\n\nasync function extractCSSVariables(): Promise<ExtractedVariables> {\n const styleSheets = Array.from(document.styleSheets);\n let cssContent = \"\";\n\n for (const sheet of styleSheets) {\n try {\n const text = Array.from(sheet.cssRules || [])\n .map((rule) => rule.cssText)\n .join(\"\\n\");\n cssContent += text;\n } catch (e) {\n // Cross-origin stylesheets will throw - skip them\n console.warn(\"Cannot access stylesheet:\", sheet.href, e);\n }\n }\n\n return extractCSSVariablesFromContent(cssContent);\n}\n\n// Global cache that persists across module reloads (for HMR)\ndeclare global {\n var __CSS_VARIABLES_CACHE__: ExtractedVariables | undefined;\n var __CSS_VARIABLES_LOADING__: boolean | undefined;\n var __CSS_VARIABLES_PROMISE__: Promise<ExtractedVariables> | undefined;\n}\n\n// Synchronous getter that returns cached variables or null if not loaded yet\nexport function getCachedCSSVariables(): ExtractedVariables | null {\n return globalThis.__CSS_VARIABLES_CACHE__ || null;\n}\n\n// Initialize CSS variables with proper global caching\nexport async function initializeCSSVariables(): Promise<ExtractedVariables> {\n // If already loaded, return cached version\n if (globalThis.__CSS_VARIABLES_CACHE__) {\n return globalThis.__CSS_VARIABLES_CACHE__;\n }\n\n // If currently loading, return the existing promise\n if (\n globalThis.__CSS_VARIABLES_LOADING__ &&\n globalThis.__CSS_VARIABLES_PROMISE__\n ) {\n return globalThis.__CSS_VARIABLES_PROMISE__;\n }\n\n // Start loading\n globalThis.__CSS_VARIABLES_LOADING__ = true;\n globalThis.__CSS_VARIABLES_PROMISE__ = extractCSSVariables()\n .then((variables) => {\n globalThis.__CSS_VARIABLES_CACHE__ = variables;\n globalThis.__CSS_VARIABLES_LOADING__ = false;\n return variables;\n })\n .catch((error) => {\n console.error(\"Failed to extract CSS variables:\", error);\n const fallback = { root: {}, dark: {}, theme: {} };\n globalThis.__CSS_VARIABLES_CACHE__ = fallback;\n globalThis.__CSS_VARIABLES_LOADING__ = false;\n return fallback;\n });\n\n return globalThis.__CSS_VARIABLES_PROMISE__;\n}\n","import colors from \"tailwindcss/colors\";\nimport defaultTheme from \"tailwindcss/defaultTheme\";\nimport { convertRemToPixels } from \"./convert-rem-to-pixels.js\";\nimport { getCachedCSSVariables } from \"./extract-variables.js\";\nimport type { ThemeToken } from \"@superblocksteam/library-shared/props\";\n\n// Cache for size presets to avoid recalculation\nlet cachedSizePresets: {\n height: ThemeToken[];\n width: ThemeToken[];\n spacing: ThemeToken[];\n} | null = null;\n\nconst height = defaultTheme.height({ theme: () => \"\", colors });\nconst width = defaultTheme.width({ theme: () => \"\", colors });\nconst minWidth = defaultTheme.minWidth({ theme: () => \"\", colors });\nconst maxWidth = defaultTheme.maxWidth({ theme: () => \"\", colors });\nconst minHeight = defaultTheme.minHeight({ theme: () => \"\", colors });\nconst maxHeight = defaultTheme.maxHeight({ theme: () => \"\", colors });\nconst spacing = defaultTheme.spacing;\n// Helper function to detect if a value looks like a size\nexport function isSizeValue(value: string): boolean {\n const trimmedValue = value.trim().toLowerCase();\n\n // Check for common size formats\n return (\n // Pixel values\n /^\\d+px$/.test(trimmedValue) ||\n // Rem values\n /^\\d+(\\.\\d+)?rem$/.test(trimmedValue) ||\n // Em values\n /^\\d+(\\.\\d+)?em$/.test(trimmedValue) ||\n // Percentage values\n /^\\d+(\\.\\d+)?%$/.test(trimmedValue) ||\n // Viewport units\n /^\\d+(\\.\\d+)?(vw|vh|vmin|vmax|dvw|dvh|lvw|lvh|svw|svh)$/.test(\n trimmedValue,\n ) ||\n // Fractional units\n /^\\d+(\\.\\d+)?(fr|ch|ex|ic|cap|lh|rlh)$/.test(trimmedValue) ||\n // CSS keywords\n [\n \"auto\",\n \"inherit\",\n \"initial\",\n \"unset\",\n \"revert\",\n \"revert-layer\",\n \"max-content\",\n \"min-content\",\n \"fit-content\",\n \"stretch\",\n \"none\",\n \"0\",\n \"1\",\n \"2\",\n \"3\",\n \"4\",\n \"5\",\n \"6\",\n \"7\",\n \"8\",\n \"9\",\n \"10\",\n \"11\",\n \"12\",\n \"14\",\n \"16\",\n \"20\",\n \"24\",\n \"28\",\n \"32\",\n \"36\",\n \"40\",\n \"44\",\n \"48\",\n \"52\",\n \"56\",\n \"60\",\n \"64\",\n \"72\",\n \"80\",\n \"96\",\n ].includes(trimmedValue)\n );\n}\n\nexport function getSizePresets() {\n if (cachedSizePresets) {\n return cachedSizePresets;\n }\n\n const cssVariables = getCachedCSSVariables();\n if (!cssVariables) {\n return [];\n }\n\n const sizePresets: ThemeToken[] = [];\n\n const addCssSize = (prop: string, value: string) => {\n if (isSizeValue(value)) {\n const label = prop.replace(\"--\", \"\").replace(/-/g, \" \");\n sizePresets.push({\n label,\n value: `(${prop})`,\n rawValue: convertRemToPixels(value),\n type: \"system\" as const,\n });\n }\n };\n\n // Extract size variables from root\n for (const [prop, value] of Object.entries(cssVariables.root)) {\n addCssSize(prop, value);\n }\n\n // Extract size variables from theme\n for (const [prop, value] of Object.entries(cssVariables.theme)) {\n addCssSize(prop, value);\n }\n\n // Extract size variables from dark theme\n for (const [prop, value] of Object.entries(cssVariables.dark)) {\n addCssSize(prop, value);\n }\n\n // add spacing to size presets\n for (const [key, value] of Object.entries(spacing)) {\n sizePresets.push({\n label: key,\n value: key,\n rawValue: convertRemToPixels(value),\n type: \"tailwind\" as const,\n });\n }\n\n const allWidth = { ...width, ...minWidth, ...maxWidth };\n const allHeight = { ...height, ...minHeight, ...maxHeight };\n\n const heightPresets = [...sizePresets];\n const widthPresets = [...sizePresets];\n for (const [key, value] of Object.entries(allWidth)) {\n if (typeof value === \"string\") {\n widthPresets.push({\n label: key,\n value: key,\n rawValue: convertRemToPixels(value),\n type: \"tailwind\" as const,\n });\n }\n }\n\n // Add Tailwind CSS default height values\n for (const [key, value] of Object.entries(allHeight)) {\n if (typeof value === \"string\") {\n heightPresets.push({\n label: key,\n value: key,\n rawValue: convertRemToPixels(value),\n type: \"tailwind\" as const,\n });\n }\n }\n\n // Remove duplicates\n const seen = new Set<string>();\n const uniqueHeightPresets = heightPresets.filter((preset) => {\n if (seen.has(preset.value)) return false;\n seen.add(preset.value);\n return true;\n });\n\n seen.clear();\n const uniqueWidthPresets = widthPresets.filter((preset) => {\n if (seen.has(preset.value)) return false;\n seen.add(preset.value);\n return true;\n });\n\n seen.clear();\n const uniqueSpacingPresets = sizePresets.filter((preset) => {\n if (seen.has(preset.value)) return false;\n seen.add(preset.value);\n return true;\n });\n\n cachedSizePresets = {\n height: uniqueHeightPresets,\n width: uniqueWidthPresets,\n spacing: uniqueSpacingPresets,\n };\n return cachedSizePresets;\n}\n","import defaultTheme from \"tailwindcss/defaultTheme\";\nimport { convertRemToPixels } from \"./convert-rem-to-pixels.js\";\nimport { getCachedCSSVariables } from \"./extract-variables.js\";\nimport { isSizeValue } from \"./style-tokens-size.js\";\nimport type { ThemeToken } from \"@superblocksteam/library-shared/props\";\n\n// Cache for size presets to avoid recalculation\nlet cachedBorderPresets: {\n borderWidth: ThemeToken[];\n borderRadius: ThemeToken[];\n boxShadow: ThemeToken[];\n} | null = null;\n\nconst borderWidth = defaultTheme.borderWidth;\nconst borderRadius = defaultTheme.borderRadius;\nconst boxShadow = defaultTheme.boxShadow;\n\nconst DEFAULT_KEY = \"DEFAULT\";\n\n// Helper function to detect if a value looks like a box shadow\nfunction isBoxShadowValue(value: string): boolean {\n const trimmedValue = value.trim().toLowerCase();\n const isBoxShadow =\n /^(0|none|inset|outset|shadow-sm|shadow|shadow-md|shadow-lg|shadow-xl|shadow-2xl|shadow-inner|shadow-none)$/.test(\n trimmedValue,\n );\n if (isBoxShadow) {\n return true;\n }\n // Box shadow format: [inset?] [x] [y] [blur?] [spread?] [color?]\n // Can have multiple comma-separated shadows\n const customBoxShadowPattern =\n /^(inset\\s+)?(-?\\d+(\\.\\d+)?(px|rem|em|%)?(\\s+|$)){2,4}([a-z]+\\(.*?\\)|#[0-9a-f]{3,8}|[a-z]+)?(\\s*,\\s*(inset\\s+)?(-?\\d+(\\.\\d+)?(px|rem|em|%)?(\\s+|$)){2,4}([a-z]+\\(.*?\\)|#[0-9a-f]{3,8}|[a-z]+)?)*$/i;\n\n return isBoxShadow || customBoxShadowPattern.test(trimmedValue);\n}\n\n// Helper function to format label - lowercases the text\nfunction formatLabel(key: string): string {\n return key.toLowerCase();\n}\n\nexport function getBorderPresets() {\n if (cachedBorderPresets) {\n return cachedBorderPresets;\n }\n\n const cssVariables = getCachedCSSVariables();\n if (!cssVariables) {\n return [];\n }\n\n const sizePresets: ThemeToken[] = [];\n const boxShadowPresets: ThemeToken[] = [];\n\n const addCssSize = (prop: string, value: string) => {\n if (isSizeValue(value)) {\n const label = formatLabel(prop.replace(\"--\", \"\").replace(/-/g, \" \"));\n sizePresets.push({\n label,\n value: `(${prop})`,\n rawValue: convertRemToPixels(value),\n type: \"system\" as const,\n });\n } else if (isBoxShadowValue(value)) {\n const label = formatLabel(prop.replace(\"--\", \"\").replace(/-/g, \" \"));\n boxShadowPresets.push({\n label,\n value: `(${prop})`,\n rawValue: value,\n type: \"system\" as const,\n });\n }\n };\n\n // Extract svariables from root\n for (const [prop, value] of Object.entries(cssVariables.root)) {\n addCssSize(prop, value);\n }\n\n // Extract variables from theme\n for (const [prop, value] of Object.entries(cssVariables.theme)) {\n addCssSize(prop, value);\n }\n\n // Extract variables from dark theme\n for (const [prop, value] of Object.entries(cssVariables.dark)) {\n addCssSize(prop, value);\n }\n // add things from the theme to each of the presets\n const borderWidthPresets = [...sizePresets];\n const borderRadiusPresets = [...sizePresets];\n\n function addTailwindProperty(\n presets: ThemeToken[],\n key: string,\n value: unknown,\n valueConverter?: (value: string) => string,\n ) {\n if (key === DEFAULT_KEY && typeof value === \"string\") {\n presets.push({\n label: \"default\",\n value: \"\", // empty string (i.e. \"border\" or \"rounded\")\n rawValue: valueConverter\n ? valueConverter(value)\n : convertRemToPixels(value),\n type: \"tailwind\" as const,\n });\n } else if (typeof value === \"string\") {\n presets.push({\n label: formatLabel(key),\n value: key,\n rawValue: valueConverter\n ? valueConverter(value)\n : convertRemToPixels(value),\n type: \"tailwind\" as const,\n });\n }\n }\n\n for (const [key, value] of Object.entries(borderWidth)) {\n addTailwindProperty(borderWidthPresets, key, value, convertRemToPixels);\n }\n\n for (const [key, value] of Object.entries(borderRadius)) {\n addTailwindProperty(borderRadiusPresets, key, value, convertRemToPixels);\n }\n\n for (const [key, value] of Object.entries(boxShadow)) {\n addTailwindProperty(boxShadowPresets, key, value);\n }\n\n // Remove duplicates\n const seen = new Set<string>();\n const uniqueBorderWidthPresets = borderWidthPresets.filter((preset) => {\n if (seen.has(preset.value)) return false;\n seen.add(preset.value);\n return true;\n });\n\n seen.clear();\n const uniqueBorderRadiusPresets = borderRadiusPresets.filter((preset) => {\n if (seen.has(preset.value)) return false;\n seen.add(preset.value);\n return true;\n });\n\n seen.clear();\n const uniqueBoxShadowPresets = boxShadowPresets.filter((preset) => {\n if (seen.has(preset.value)) return false;\n seen.add(preset.value);\n return true;\n });\n\n cachedBorderPresets = {\n borderWidth: uniqueBorderWidthPresets,\n borderRadius: uniqueBorderRadiusPresets,\n boxShadow: uniqueBoxShadowPresets,\n };\n return cachedBorderPresets;\n}\n","import colors from \"tailwindcss/colors\";\nimport { getCachedCSSVariables } from \"./extract-variables.js\";\nimport type { ThemeToken } from \"@superblocksteam/library-shared/props\";\n\n// Cache for color presets to avoid recalculation\nlet cachedColorPresets: ThemeToken[] | null = null;\n\n// Helper function to detect if a value looks like a color\nfunction isColorValue(value: string): boolean {\n const trimmedValue = value.trim().toLowerCase();\n\n // Check for common color formats\n return (\n trimmedValue.startsWith(\"#\") || // Hex colors\n trimmedValue.startsWith(\"rgb(\") || // RGB\n trimmedValue.startsWith(\"rgba(\") || // RGBA\n trimmedValue.startsWith(\"hsl(\") || // HSL\n trimmedValue.startsWith(\"hsla(\") || // HSLA\n trimmedValue.startsWith(\"oklch(\") || // OKLCH\n trimmedValue.startsWith(\"oklab(\") || // OKLAB\n trimmedValue.startsWith(\"lch(\") || // LCH\n trimmedValue.startsWith(\"lab(\") || // LAB\n trimmedValue.startsWith(\"color(\") || // CSS Color Module Level 4\n trimmedValue.startsWith(\"hwb(\") || // HWB\n // Common CSS color keywords\n [\n \"transparent\",\n \"currentcolor\",\n \"inherit\",\n \"initial\",\n \"unset\",\n \"red\",\n \"blue\",\n \"green\",\n \"black\",\n \"white\",\n \"gray\",\n \"yellow\",\n \"orange\",\n \"purple\",\n \"pink\",\n \"brown\",\n ].includes(trimmedValue)\n );\n}\n\nexport function getColorPresets() {\n if (cachedColorPresets) {\n return cachedColorPresets;\n }\n\n const cssVariables = getCachedCSSVariables();\n if (!cssVariables) {\n return [];\n }\n\n const colorPresets = [];\n\n const addCssColor = (prop: string, value: string) => {\n if (isColorValue(value)) {\n const label = prop.replace(\"--\", \"\").replace(/-/g, \" \");\n colorPresets.push({\n label,\n value: prop.replace(\"--\", \"\"),\n rawValue: value,\n type: \"system\" as const,\n });\n }\n };\n\n // Extract color variables from root\n for (const [prop, value] of Object.entries(cssVariables.root)) {\n addCssColor(prop, value);\n }\n\n // Extract color variables from theme\n for (const [prop, value] of Object.entries(cssVariables.theme)) {\n addCssColor(prop, value);\n }\n\n // from dark colors\n for (const [prop, value] of Object.entries(cssVariables.dark)) {\n addCssColor(prop, value);\n }\n\n // Add Tailwind CSS default colors\n for (const [colorName, colorShades] of Object.entries(colors)) {\n if (typeof colorShades === \"object\" && colorShades !== null) {\n // Handle color objects with shades (like red.100, red.200, etc.)\n for (const [shade, colorValue] of Object.entries(colorShades)) {\n if (typeof colorValue === \"string\") {\n colorPresets.push({\n label: `${colorName} ${shade}`,\n value: `${colorName}-${shade}`,\n rawValue: colorValue,\n type: \"tailwind\" as const,\n });\n }\n }\n } else if (typeof colorShades === \"string\") {\n // Handle single color values (like transparent, current, etc.)\n colorPresets.push({\n label: colorName,\n value: colorName,\n rawValue: colorShades,\n type: \"tailwind\" as const,\n });\n }\n }\n\n // Remove duplicates\n const seen = new Set<string>();\n const uniquePresets = colorPresets.filter((preset) => {\n if (seen.has(preset.value)) return false;\n seen.add(preset.value);\n return true;\n });\n\n cachedColorPresets = uniquePresets;\n return uniquePresets;\n}\n","import { Prop, PropsCategory, Section } from \"../props-builder.js\";\nimport { getBorderPresets } from \"./style-tokens-border.js\";\nimport { getColorPresets } from \"./style-tokens-color.js\";\nimport { getSizePresets } from \"./style-tokens-size.js\";\nimport type { TailwindPropertyKey } from \"@superblocksteam/library-shared\";\n\n/**\n * Creates a standardized styles section for use in properties panels.\n * This provides a consistent interface for applying Tailwind CSS classes across components.\n *\n * @example\n * // Basic usage with defaults\n * styles: tailwindStylesCategory()\n *\n * // Override with prioritizedTailwindProperties. These properties will always be shown in the properties panel, event when not set.\n * styles: tailwindStylesCategory({prioritizedTailwindProperties: [\"rounded\", \"text-color\"]})\n *\n * @param options - Configuration options to override defaults\n * @returns A Section with PropsCategory.Styles containing a className prop\n */\nexport const tailwindStylesCategory = (props?: {\n prioritizedTailwindProperties?: TailwindPropertyKey[];\n}): Section<{ className: string }> => {\n const { prioritizedTailwindProperties } = props ?? {};\n return Section.category(PropsCategory.Appearance).children({\n className: Prop.string().propertiesPanel({\n controlType: \"TAILWIND_CLASS_BUILDER\" as const,\n themePresets: function () {\n return {\n ...getSizePresets(),\n ...getBorderPresets(),\n colors: getColorPresets(),\n };\n },\n prioritizedTailwindProperties,\n }),\n });\n};\n","import { registerComponentInternal } from \"../../internal-index.js\";\nimport { inlineStylesCategory } from \"../../properties-panel/mixins/inline-styles-category.js\";\nimport { tailwindStylesCategory } from \"../../properties-panel/mixins/styles-category.js\";\nimport {\n Section,\n PropsCategory,\n type SectionPropRecord,\n} from \"../../properties-panel/props-builder.js\";\nimport type { Prop } from \"../../properties-panel/props-builder.js\";\nimport type React from \"react\";\n\nexport type PropertiesPanelDefinition<Props extends React.ComponentProps<any>> =\n\n | SectionPropRecord<Props>\n | {\n [K in string]: Section<Props, SectionPropRecord<Props>>;\n };\n\nconst defaultSectionsTemplate = () => ({\n appearance: tailwindStylesCategory(),\n styles: inlineStylesCategory(),\n});\n\nfunction convertToSections(\n propertiesDefinition: Record<string, Prop<any>>,\n): Record<string, Section<any, any>> {\n const contentSection = Section.category(PropsCategory.Content).children(\n Object.fromEntries(\n Object.entries(propertiesDefinition).filter(\n ([, prop]) => prop.type !== \"eventHandler\",\n ),\n ),\n );\n\n const eventSection = Section.category(PropsCategory.EventHandlers).children(\n Object.fromEntries(\n Object.entries(propertiesDefinition).filter(\n ([, prop]) => prop.type === \"eventHandler\",\n ),\n ),\n );\n\n return {\n content: contentSection,\n events: eventSection,\n };\n}\n\nfunction mergeSections(\n sections: Record<string, Section<any, any>>,\n defaultSections: Record<string, Section<any, any>>,\n): Record<string, Section<any, any>> {\n const allCurrentProps = Object.values(sections).flatMap((section) =>\n Object.keys(section.props),\n );\n\n Object.entries(defaultSections).forEach(([sectionName, section]) => {\n Object.entries(section.props).forEach(([propName, prop]) => {\n if (!allCurrentProps.includes(propName)) {\n if (!sections[sectionName]) {\n sections[sectionName] =\n defaultSections[sectionName as keyof typeof defaultSections];\n }\n sections[sectionName].add({ [propName]: prop } as Record<\n string,\n Prop<any>\n >);\n }\n });\n });\n\n return sections;\n}\n\n/**\n * Registers a custom React component or HTML element with Superblocks.\n *\n * @param component - The React component or HTML element name (e.g., \"div\") to register\n * @param propertiesDefinition - Optional properties panel definition, either as flat props or organized into sections\n * @returns The registered component\n *\n * @example\n * ```tsx\n * // Register HTML element with just defaults\n * registerComponent(\"div\");\n *\n * // Register HTML element with custom props\n * registerComponent(\"div\", {\n * children: Prop.node(),\n * onClick: Prop.eventHandler(),\n * });\n *\n * // Flat props (auto-categorized into Content and Event sections)\n * registerComponent(MyComponent, {\n * label: Prop.string().default(\"Click me\"),\n * onClick: Prop.eventHandler(),\n * });\n *\n * // Organized into sections\n * registerComponent(MyComponent, {\n * content: Section.category(PropsCategory.Content).children({\n * label: Prop.string().default(\"Click me\"),\n * }),\n * events: Section.category(PropsCategory.EventHandlers).children({\n * onClick: Prop.eventHandler(),\n * }),\n * });\n * ```\n */\nexport function registerComponent<T extends React.ElementType>(\n component: T,\n propertiesDefinition?: PropertiesPanelDefinition<React.ComponentProps<T>>,\n): ReturnType<typeof registerComponentInternal> {\n const defaultSections = defaultSectionsTemplate();\n\n // If no properties provided, just use defaults\n if (!propertiesDefinition) {\n return registerComponentInternal(component, defaultSections);\n }\n\n const containsSections = Object.values(propertiesDefinition).every(\n (prop) => prop instanceof Section,\n );\n\n const allSections = containsSections\n ? mergeSections(\n propertiesDefinition as Record<string, Section<any, any>>,\n defaultSections,\n )\n : mergeSections(\n convertToSections(propertiesDefinition as Record<string, Prop<any>>),\n defaultSections,\n );\n\n return registerComponentInternal(component, allSections);\n}\n","import { tailwindStylesCategory } from \"../../properties-panel/mixins/styles-category.js\";\nimport {\n Prop,\n PropsCategory,\n Section,\n} from \"../../properties-panel/props-builder.js\";\nimport type { PropertiesPanelDefinition } from \"../custom/register-custom-component.js\";\nimport type { TailwindPropertyKey } from \"@superblocksteam/library-shared\";\n\n// Typography-focused Tailwind properties that should be prioritized for text elements\nconst TYPOGRAPHY_PRIORITIZED_PROPERTIES: TailwindPropertyKey[] = [\n \"font-family\",\n \"font-size\",\n \"font-weight\",\n \"font-style\",\n \"line-height\",\n \"letter-spacing\",\n \"text-align\",\n \"text-color\",\n \"text-decoration\",\n \"text-transform\",\n];\n\n// Container-focused Tailwind properties that should be prioritized for container elements\nconst CONTAINER_PRIORITIZED_PROPERTIES: TailwindPropertyKey[] = [\n \"display\",\n // Spacing\n \"p\",\n \"m\",\n // Sizing\n \"width\",\n \"height\",\n // Background\n \"background-color\",\n // Borders (order matches UI: radius, width+color, style)\n \"rounded\",\n \"border-width\",\n \"border-style\",\n // Overflow\n \"overflow\",\n];\n\nexport const htmlTagSectionsTemplate = (params: {\n hasChildren: boolean;\n prioritizedTailwindProperties?: TailwindPropertyKey[];\n}): PropertiesPanelDefinition<React.ComponentProps<any>> => {\n const sections: PropertiesPanelDefinition<React.ComponentProps<any>> = {};\n\n // Add content section for elements with children\n if (params.hasChildren) {\n sections.contentSection = Section.category(PropsCategory.Content).children({\n children: Prop.jsx().propertiesPanel({\n label: \"Children\",\n description: \"The content of the element\",\n }),\n });\n }\n\n // Add styles section with optional prioritized properties\n sections.appearance = tailwindStylesCategory({\n prioritizedTailwindProperties: params.prioritizedTailwindProperties,\n });\n\n return sections;\n};\n\nexport const htmlTagSectionsTemplateForTypography =\n (): PropertiesPanelDefinition<React.ComponentProps<any>> => {\n return htmlTagSectionsTemplate({\n hasChildren: true,\n prioritizedTailwindProperties: TYPOGRAPHY_PRIORITIZED_PROPERTIES,\n });\n };\n\nexport const htmlTagSectionsTemplateForContainers =\n (): PropertiesPanelDefinition<React.ComponentProps<any>> => {\n return htmlTagSectionsTemplate({\n hasChildren: true,\n prioritizedTailwindProperties: CONTAINER_PRIORITIZED_PROPERTIES,\n });\n };\n","/**\n * Register all common HTML elements with default properties panels.\n * This enables all standard HTML elements to work seamlessly in the Superblocks editor\n * with automatic className and style properties.\n */\nimport { registerComponent } from \"../custom/register-custom-component.js\";\nimport {\n htmlTagSectionsTemplate,\n htmlTagSectionsTemplateForContainers,\n htmlTagSectionsTemplateForTypography,\n} from \"./html-property-panels.js\";\n\nlet registered = false;\n\n/**\n * Registers all standard HTML elements with default properties panels.\n * This is called automatically when the library is imported.\n */\nexport function registerHtmlElements() {\n // Only register once\n if (registered) {\n return;\n }\n registered = true;\n\n // Structural elements\n registerComponent(\"div\", htmlTagSectionsTemplateForContainers());\n registerComponent(\"section\", htmlTagSectionsTemplateForContainers());\n registerComponent(\"article\", htmlTagSectionsTemplateForContainers());\n registerComponent(\"header\", htmlTagSectionsTemplateForContainers());\n registerComponent(\"footer\", htmlTagSectionsTemplateForContainers());\n registerComponent(\"main\", htmlTagSectionsTemplateForContainers());\n registerComponent(\"aside\", htmlTagSectionsTemplateForContainers());\n registerComponent(\"nav\", htmlTagSectionsTemplateForContainers());\n registerComponent(\"address\", htmlTagSectionsTemplateForContainers());\n registerComponent(\"hgroup\", htmlTagSectionsTemplateForContainers());\n\n // Headings and text\n registerComponent(\"span\", htmlTagSectionsTemplateForTypography());\n registerComponent(\"h1\", htmlTagSectionsTemplateForTypography());\n registerComponent(\"h2\", htmlTagSectionsTemplateForTypography());\n registerComponent(\"h3\", htmlTagSectionsTemplateForTypography());\n registerComponent(\"h4\", htmlTagSectionsTemplateForTypography());\n registerComponent(\"h5\", htmlTagSectionsTemplateForTypography());\n registerComponent(\"h6\", htmlTagSectionsTemplateForTypography());\n registerComponent(\"p\", htmlTagSectionsTemplateForTypography());\n registerComponent(\"a\", htmlTagSectionsTemplateForTypography());\n registerComponent(\"strong\", htmlTagSectionsTemplateForTypography());\n registerComponent(\"em\", htmlTagSectionsTemplateForTypography());\n registerComponent(\"code\", htmlTagSectionsTemplateForTypography());\n registerComponent(\"pre\", htmlTagSectionsTemplateForTypography());\n registerComponent(\"blockquote\", htmlTagSectionsTemplateForTypography());\n registerComponent(\"abbr\", htmlTagSectionsTemplateForTypography());\n registerComponent(\"small\", htmlTagSectionsTemplateForTypography());\n registerComponent(\"mark\", htmlTagSectionsTemplateForTypography());\n registerComponent(\"del\", htmlTagSectionsTemplateForTypography());\n registerComponent(\"ins\", htmlTagSectionsTemplateForTypography());\n registerComponent(\"sub\", htmlTagSectionsTemplateForTypography());\n registerComponent(\"sup\", htmlTagSectionsTemplateForTypography());\n registerComponent(\"cite\", htmlTagSectionsTemplateForTypography());\n registerComponent(\"dfn\", htmlTagSectionsTemplateForTypography());\n registerComponent(\"kbd\", htmlTagSectionsTemplateForTypography());\n registerComponent(\"samp\", htmlTagSectionsTemplateForTypography());\n registerComponent(\"var\", htmlTagSectionsTemplateForTypography());\n registerComponent(\"s\", htmlTagSectionsTemplateForTypography());\n registerComponent(\"q\", htmlTagSectionsTemplateForTypography());\n registerComponent(\"u\", htmlTagSectionsTemplateForTypography());\n registerComponent(\"b\", htmlTagSectionsTemplateForTypography());\n registerComponent(\"i\", htmlTagSectionsTemplateForTypography());\n registerComponent(\"bdi\", htmlTagSectionsTemplateForTypography());\n registerComponent(\"bdo\", htmlTagSectionsTemplateForTypography());\n registerComponent(\"ruby\", htmlTagSectionsTemplateForTypography());\n registerComponent(\"rt\", htmlTagSectionsTemplateForTypography());\n registerComponent(\"rp\", htmlTagSectionsTemplateForTypography());\n\n // Form elements\n registerComponent(\"form\", htmlTagSectionsTemplate({ hasChildren: true }));\n registerComponent(\"input\", htmlTagSectionsTemplate({ hasChildren: false }));\n registerComponent(\"button\", htmlTagSectionsTemplateForTypography());\n registerComponent(\"textarea\", htmlTagSectionsTemplateForTypography());\n registerComponent(\"select\", htmlTagSectionsTemplate({ hasChildren: true }));\n registerComponent(\"option\", htmlTagSectionsTemplateForTypography());\n registerComponent(\"label\", htmlTagSectionsTemplateForTypography());\n registerComponent(\"fieldset\", htmlTagSectionsTemplate({ hasChildren: true }));\n registerComponent(\"legend\", htmlTagSectionsTemplateForTypography());\n registerComponent(\"datalist\", htmlTagSectionsTemplate({ hasChildren: true }));\n registerComponent(\"output\", htmlTagSectionsTemplate({ hasChildren: true }));\n registerComponent(\"progress\", htmlTagSectionsTemplate({ hasChildren: true }));\n registerComponent(\"meter\", htmlTagSectionsTemplate({ hasChildren: true }));\n\n // List elements\n registerComponent(\"ul\", htmlTagSectionsTemplate({ hasChildren: true }));\n registerComponent(\"ol\", htmlTagSectionsTemplate({ hasChildren: true }));\n registerComponent(\"li\", htmlTagSectionsTemplateForTypography());\n registerComponent(\"dl\", htmlTagSectionsTemplate({ hasChildren: true }));\n registerComponent(\"dt\", htmlTagSectionsTemplateForTypography());\n registerComponent(\"dd\", htmlTagSectionsTemplateForTypography());\n\n // Table elements\n registerComponent(\"table\", htmlTagSectionsTemplate({ hasChildren: true }));\n registerComponent(\"thead\", htmlTagSectionsTemplate({ hasChildren: true }));\n registerComponent(\"tbody\", htmlTagSectionsTemplate({ hasChildren: true }));\n registerComponent(\"tfoot\", htmlTagSectionsTemplate({ hasChildren: true }));\n registerComponent(\"tr\", htmlTagSectionsTemplate({ hasChildren: true }));\n registerComponent(\"th\", htmlTagSectionsTemplateForTypography());\n registerComponent(\"td\", htmlTagSectionsTemplateForTypography());\n registerComponent(\"caption\", htmlTagSectionsTemplateForTypography());\n registerComponent(\"colgroup\", htmlTagSectionsTemplate({ hasChildren: true }));\n registerComponent(\"col\", htmlTagSectionsTemplate({ hasChildren: false }));\n\n // Media elements\n registerComponent(\"img\", htmlTagSectionsTemplate({ hasChildren: false }));\n registerComponent(\"video\", htmlTagSectionsTemplate({ hasChildren: true }));\n registerComponent(\"audio\", htmlTagSectionsTemplate({ hasChildren: true }));\n registerComponent(\"source\", htmlTagSectionsTemplate({ hasChildren: false }));\n registerComponent(\"track\", htmlTagSectionsTemplate({ hasChildren: false }));\n registerComponent(\"canvas\", htmlTagSectionsTemplate({ hasChildren: true }));\n registerComponent(\"svg\", htmlTagSectionsTemplate({ hasChildren: true }));\n registerComponent(\"picture\", htmlTagSectionsTemplate({ hasChildren: true }));\n registerComponent(\"figure\", htmlTagSectionsTemplate({ hasChildren: true }));\n registerComponent(\n \"figcaption\",\n htmlTagSectionsTemplate({ hasChildren: true }),\n );\n\n // Embedded content\n registerComponent(\"iframe\", htmlTagSectionsTemplate({ hasChildren: true }));\n registerComponent(\"embed\", htmlTagSectionsTemplate({ hasChildren: false }));\n registerComponent(\"object\", htmlTagSectionsTemplate({ hasChildren: true }));\n registerComponent(\"param\", htmlTagSectionsTemplate({ hasChildren: false }));\n\n // Interactive elements\n registerComponent(\"details\", htmlTagSectionsTemplate({ hasChildren: true }));\n registerComponent(\"summary\", htmlTagSectionsTemplateForTypography());\n registerComponent(\"dialog\", htmlTagSectionsTemplate({ hasChildren: true }));\n registerComponent(\"menu\", htmlTagSectionsTemplate({ hasChildren: true }));\n\n // Miscellaneous\n registerComponent(\"hr\", htmlTagSectionsTemplate({ hasChildren: false }));\n registerComponent(\"br\", htmlTagSectionsTemplate({ hasChildren: false }));\n registerComponent(\"wbr\", htmlTagSectionsTemplate({ hasChildren: false }));\n registerComponent(\"time\", htmlTagSectionsTemplate({ hasChildren: true }));\n registerComponent(\"data\", htmlTagSectionsTemplate({ hasChildren: true }));\n registerComponent(\"template\", htmlTagSectionsTemplate({ hasChildren: true }));\n registerComponent(\"slot\", htmlTagSectionsTemplate({ hasChildren: true }));\n\n // Self-closing elements that don't accept children\n registerComponent(\"area\", htmlTagSectionsTemplate({ hasChildren: false }));\n registerComponent(\"base\", htmlTagSectionsTemplate({ hasChildren: false }));\n registerComponent(\"keygen\", htmlTagSectionsTemplate({ hasChildren: false }));\n registerComponent(\"link\", htmlTagSectionsTemplate({ hasChildren: false }));\n registerComponent(\"meta\", htmlTagSectionsTemplate({ hasChildren: false }));\n}\n","import rootStore from \"./lib/root-store.js\";\nimport type { IframeEventHandler } from \"./lib/iframe.js\";\n\nexport const handleBootstrapResponse: IframeEventHandler<\n \"sb-bootstrap-response\"\n> = (event) => {\n rootStore.applicationId = event.data.payload.appId;\n rootStore.userId = event.data.payload.userId;\n rootStore.apis.agentUrls =\n event.data.payload.agentUrls ??\n (event.data.payload.agentUrl ? [event.data.payload.agentUrl] : []);\n rootStore.apis.setTokens(\n event.data.payload.token,\n event.data.payload.accessToken,\n );\n\n rootStore.apis.notifyBootstrapComplete();\n\n const windowOriginUrl = event.data.payload.logContext\n .superblocks_window_origin_url as string;\n rootStore.windowOriginUrl = windowOriginUrl;\n\n if (rootStore.windowOriginUrl) {\n import(\"../utils.js\").then(({ initTracerProviderWithOrigin }) => {\n initTracerProviderWithOrigin(rootStore.windowOriginUrl!);\n\n // Initialize logging with full context\n import(\"../tracing/logs.js\").then(({ initLibraryLoggerProvider }) => {\n initLibraryLoggerProvider({\n windowOriginUrl: rootStore.windowOriginUrl!,\n appId: event.data.payload.appId,\n userId: event.data.payload.logContext.superblocks_user_id as string,\n userEmail: event.data.payload.logContext\n .superblocks_user_email as string,\n orgId: event.data.payload.logContext.superblocks_org_id as string,\n orgName: event.data.payload.logContext.superblocks_org_name as string,\n environment: event.data.payload.logContext.superblocks_env as string,\n });\n });\n });\n }\n};\n","import styled from \"styled-components\";\n\nexport const Spinner = styled.span`\n width: 50px;\n height: 50px;\n border: 4px solid #e0e1e5;\n border-bottom-color: #8c95a1;\n border-radius: 50%;\n display: inline-block;\n box-sizing: border-box;\n animation: rotation 0.5s linear infinite;\n\n @keyframes rotation {\n 0% {\n transform: rotate(0deg);\n }\n 100% {\n transform: rotate(360deg);\n }\n }\n`;\n\nexport const FullPageSpinner = () => {\n return (\n <div\n style={{\n display: \"flex\",\n justifyContent: \"center\",\n alignItems: \"center\",\n height: \"100svh\",\n width: \"100%\",\n }}\n >\n <Spinner />\n </div>\n );\n};\n","// import TokenProvider from \"../../TokenProvider\";\n\nimport { useMemo } from \"react\";\n\n// export const userApi = createApi({\n// reducerPath: \"userApi\",\n// baseQuery: fetchBaseQuery({\n// baseUrl: \"https://dev.superblocks.com/api/v1/\",\n// prepareHeaders(headers) {\n// headers.set(\"Authorization\", `Bearer ${TokenProvider.getToken()}`);\n// return headers;\n// },\n// }),\n// endpoints: (builder) => ({\n// getCurrentUser: builder.query({\n// query: () => ({\n// url: \"/users/me\",\n// responseHandler: async (response) => {\n// const data = await response.json();\n// lastRenderedProps.Global = {\n// user: data.data.user,\n// };\n// console.log(\"retrieved user\", data.data.user);\n// return data;\n// },\n// }),\n// }),\n// }),\n// });\n\nexport function useGetCurrentUserQuery() {\n return useMemo(() => {\n return {\n isLoading: false,\n data: {\n user: {\n name: \"Test User\",\n },\n },\n };\n }, []);\n}\n","import { useCallback } from \"react\";\nimport { useJSXContext } from \"../../edit-mode/jsx-wrapper.js\";\nimport { isEditMode } from \"./is-edit-mode.js\";\nimport rootStore from \"./lib/root-store.js\";\n\ndeclare global {\n // eslint-disable-next-line @typescript-eslint/no-empty-object-type\n interface SuperblocksAPIRegistry {\n // the plugin injects this during dev time\n }\n}\n\ntype RegisteredAPINames = keyof SuperblocksAPIRegistry;\n\n// Helper type to extract API interfaces from registry\ntype ApiInterfaces<Name extends string> =\n Name extends keyof SuperblocksAPIRegistry\n ? SuperblocksAPIRegistry[Name] extends { input: infer I; output: infer O }\n ? { input: I; output: O }\n : { input: Record<string, unknown>; output: any }\n : { input: never; output: never };\n\nexport const getApiPath = (name: RegisteredAPINames) => {\n let apiPath = name as string;\n if (!apiPath.startsWith(\"/apis\")) {\n apiPath = `/apis/${name}/api.yaml`;\n }\n return apiPath;\n};\n\nexport function useApiStateful<\n Name extends RegisteredAPINames,\n Inputs = ApiInterfaces<Name>[\"input\"],\n Response = ApiInterfaces<Name>[\"output\"],\n>(\n name: Name,\n): {\n run: (inputs?: Inputs) => Promise<Response | undefined>;\n cancel: () => Promise<void>;\n} {\n const { sourceId } = useJSXContext();\n\n const run = useCallback(\n async (inputs?: Inputs): Promise<Response | undefined> => {\n const apiPath = getApiPath(name);\n\n const editMode = isEditMode();\n\n const result = await rootStore.apis.runApiByPath({\n path: apiPath,\n inputs: inputs ?? {},\n ...(editMode ? { injectedCallerId: sourceId } : {}),\n });\n\n return result.data as Response;\n },\n [name, sourceId],\n );\n\n const cancel = useCallback(async () => {\n await rootStore.apis.cancelApi(name);\n }, [name]);\n\n return {\n run,\n cancel,\n };\n}\n","import * as Dialog from \"@radix-ui/react-dialog\";\nimport { isEqual } from \"lodash\";\nimport { observer } from \"mobx-react-lite\";\nimport { useEffect, useRef, useState } from \"react\";\nimport styled from \"styled-components\";\nimport {\n ErrorIconContainer,\n StyledClarkIcon,\n ErrorTitle,\n ErrorMessage,\n ErrorDetails,\n ErrorSummary,\n ErrorStack,\n ActionsContainer,\n SecondaryButton,\n} from \"../lib/internal-details/internal-components/common.js\";\nimport { FixWithClarkButton } from \"../lib/internal-details/internal-components/fix-with-clark-button.js\";\nimport { isEditMode } from \"../lib/internal-details/is-edit-mode.js\";\nimport rootStore from \"../lib/internal-details/lib/root-store.js\";\nimport { editorBridge } from \"./superblocks-editor-bridge.js\";\n\n// Global functions injected by the vanilla error overlay\ndeclare global {\n interface Window {\n __SB_MARK_APP_LOADED?: () => void;\n }\n\n // Vite HMR types for import.meta.hot\n interface ImportMeta {\n readonly hot?: {\n on: (event: string, callback: (payload: any) => void) => void;\n };\n }\n}\n\nconst ModalOverlay = styled(Dialog.Overlay)`\n position: fixed;\n inset: 0;\n background: rgba(0, 0, 0, 0.5);\n z-index: 1000;\n animation: fadeIn 0.2s ease-out;\n\n @keyframes fadeIn {\n from {\n opacity: 0;\n }\n to {\n opacity: 1;\n }\n }\n`;\n\nconst ModalContent = styled(Dialog.Content)`\n position: fixed;\n top: 50%;\n left: 50%;\n transform: translate(-50%, -50%);\n background: white;\n border-radius: 8px;\n box-shadow:\n 0 0 1px rgba(0, 0, 0, 0.1),\n 0 20px 25px -5px rgba(0, 0, 0, 0.1),\n 0 10px 10px -5px rgba(0, 0, 0, 0.04);\n max-width: 650px;\n max-height: 80vh;\n width: 90vw;\n padding: 16px;\n overflow-y: auto;\n z-index: 1001;\n animation: slideIn 0.2s ease-out;\n scrollbar-width: thin;\n\n @keyframes slideIn {\n from {\n opacity: 0;\n transform: translate(-50%, -50%) scale(0.95);\n }\n to {\n opacity: 1;\n transform: translate(-50%, -50%) scale(1);\n }\n }\n\n &:focus {\n outline: none;\n }\n`;\n\nconst InnerModalContent = styled.div`\n position: relative;\n padding: 2.5rem;\n`;\n\nconst ModalCloseButtonContainer = styled.div`\n position: sticky;\n top: 0;\n width: 100%;\n display: flex;\n justify-content: flex-end;\n`;\n\nconst ModalCloseButton = styled(Dialog.Close)`\n height: fit-content;\n background: none;\n border: none;\n color: #6c7689;\n cursor: pointer;\n padding: 4px;\n border-radius: 4px;\n transition: background-color 0.2s;\n\n &:hover {\n background-color: #f3f4f6;\n }\n\n &:focus {\n outline: 2px solid #08a4ff;\n outline-offset: 2px;\n }\n`;\n\nconst ErrorNotificationButton = styled.button`\n position: fixed;\n right: 16px;\n bottom: 16px;\n z-index: 1000;\n background: none;\n border: none;\n padding: 0;\n cursor: pointer;\n outline: none;\n`;\n\nconst ErrorNotificationContent = styled.div`\n background: #ef4444;\n color: white;\n padding: 12px 16px;\n border-radius: 6px;\n font-size: 14px;\n font-weight: 500;\n line-height: 1.4;\n max-width: 40rem;\n box-shadow:\n 0 10px 25px -5px rgba(0, 0, 0, 0.1),\n 0 8px 10px -6px rgba(0, 0, 0, 0.1);\n border: 1px solid rgba(255, 255, 255, 0.1);\n backdrop-filter: blur(10px);\n display: flex;\n align-items: center;\n gap: 8px;\n transition: all 0.2s ease;\n\n &:hover {\n transform: translateY(-2px);\n box-shadow:\n 0 20px 25px -5px rgba(0, 0, 0, 0.15),\n 0 10px 10px -5px rgba(0, 0, 0, 0.1);\n }\n`;\n\nconst ErrorText = styled.span`\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n`;\n\nconst ErrorIcon = styled.svg`\n flex-shrink: 0;\n`;\n\nexport type BuildError =\n | {\n errorType: \"import\";\n error: string;\n stack: string;\n importPath: string;\n }\n | {\n errorType: \"general\";\n error: string;\n stack?: string;\n };\n\nexport type BuildErrorModalProps = {\n isOpen: boolean;\n error: BuildError | null;\n onClose: () => void;\n};\n\nexport const BuildErrorNotification = observer(\n function BuildErrorNotification() {\n const [currentError, setCurrentError] = useState<BuildError | null>(null);\n const [isModalOpen, setIsModalOpen] = useState(false);\n const lastBuildError = useRef<BuildError | null>(null);\n\n useEffect(() => {\n // Signal to the vanilla error overlay that React has loaded\n if (typeof window !== \"undefined\" && window.__SB_MARK_APP_LOADED) {\n window.__SB_MARK_APP_LOADED();\n }\n\n // Listen to Vite's error events\n if (import.meta.hot) {\n import.meta.hot.on(\"vite:error\", (payload) => {\n const error = payload?.err || payload;\n const errorMessage = error?.message || String(error);\n\n // Parse error type based on error name or message\n let buildError: BuildError;\n\n // Check for import errors\n if (error?.name === \"ImportError\" || error?.importPath) {\n buildError = {\n errorType: \"import\",\n error: errorMessage,\n stack: error?.stack || \"\",\n importPath: error?.importPath || \"unknown\",\n };\n } else if (errorMessage.includes(\"Failed to resolve import\")) {\n // Fallback for non-custom import errors\n const importMatch = errorMessage.match(\n /Failed to resolve import [\"'](.+?)[\"']/,\n );\n buildError = {\n errorType: \"import\",\n error: errorMessage,\n stack: error?.stack || \"\",\n importPath: importMatch ? importMatch[1] : \"unknown\",\n };\n } else {\n buildError = {\n errorType: \"general\",\n error: errorMessage,\n stack: error?.stack,\n };\n }\n\n setCurrentError(buildError);\n });\n\n // Clear errors on successful updates\n import.meta.hot.on(\"vite:beforeUpdate\", () => {\n setCurrentError(null);\n setIsModalOpen(false);\n });\n\n // Mark build success after a successful HMR update so the loader can hide\n import.meta.hot.on(\"vite:afterUpdate\", () => {\n rootStore.editStore?.ai.markFirstBuildSuccess();\n });\n }\n }, []);\n\n // Auto-open modal when new error appears\n useEffect(() => {\n if (currentError && !isEqual(lastBuildError.current, currentError)) {\n setIsModalOpen(true);\n lastBuildError.current = currentError;\n editorBridge.sendLoadError(currentError.error);\n }\n }, [currentError]);\n\n // Check if AI is currently generating\n const isAIGenerating = rootStore.editStore?.ai.getIsEditing() ?? false;\n\n // During AI generation, don't show any error UI\n if (!currentError || isAIGenerating) {\n return null;\n }\n\n const displayCornerError = !isModalOpen;\n const errorText =\n currentError.errorType === \"import\" ? \"Import Error\" : \"Build Error\";\n\n return (\n <>\n <BuildErrorModal\n isOpen={isModalOpen}\n error={currentError}\n onClose={() => setIsModalOpen(false)}\n />\n {displayCornerError ? (\n <ErrorNotificationButton onClick={() => setIsModalOpen(true)}>\n <ErrorNotificationContent>\n <ErrorIcon\n width=\"16\"\n height=\"16\"\n viewBox=\"0 0 16 16\"\n fill=\"currentColor\"\n >\n <path d=\"M8 1.5a6.5 6.5 0 100 13 6.5 6.5 0 000-13zM0 8a8 8 0 1116 0A8 8 0 010 8z\" />\n <path d=\"M7.002 11a1 1 0 112 0 1 1 0 01-2 0zM7.1 4.995a.905.905 0 111.8 0l-.35 3.507a.552.552 0 01-1.1 0L7.1 4.995z\" />\n </ErrorIcon>\n <ErrorText>{errorText}</ErrorText>\n </ErrorNotificationContent>\n </ErrorNotificationButton>\n ) : null}\n </>\n );\n },\n);\n\nexport function BuildErrorModal({\n isOpen,\n error,\n onClose,\n}: BuildErrorModalProps) {\n if (!error) return null;\n\n const title = error.errorType === \"import\" ? \"Import error\" : \"Build error\";\n const message =\n error.errorType === \"import\" ? (\n <>\n Error importing <code>{error.importPath}</code>\n </>\n ) : (\n \"An error occurred during the build process\"\n );\n\n // Combine error message with stack trace for full details\n const details =\n error.stack && error.stack.trim()\n ? `${error.error}\\n${error.stack}`\n : error.error;\n\n // Create an Error object for FixWithClarkButton\n const errorObj = new Error(error.error);\n errorObj.stack = details || error.error;\n if (error.errorType === \"import\") {\n errorObj.name = \"ImportError\";\n }\n\n return (\n <Dialog.Root open={isOpen} onOpenChange={onClose}>\n <Dialog.Portal>\n <ModalOverlay />\n <ModalContent data-test=\"build-error-modal\">\n <ModalCloseButtonContainer>\n <ModalCloseButton aria-label=\"Close error dialog\">\n <svg\n width=\"16\"\n height=\"16\"\n viewBox=\"0 0 16 16\"\n fill=\"currentColor\"\n >\n <path d=\"M12.8 4.4L11.6 3.2 8 6.8 4.4 3.2 3.2 4.4 6.8 8 3.2 11.6 4.4 12.8 8 9.2 11.6 12.8 12.8 11.6 9.2 8z\" />\n </svg>\n </ModalCloseButton>\n </ModalCloseButtonContainer>\n\n <InnerModalContent>\n <ErrorIconContainer>\n <StyledClarkIcon />\n </ErrorIconContainer>\n\n <Dialog.Title asChild>\n <ErrorTitle>{title}</ErrorTitle>\n </Dialog.Title>\n\n <ErrorMessage data-test=\"build-error-message\">\n {message}\n </ErrorMessage>\n\n <ActionsContainer>\n {isEditMode() && (\n <FixWithClarkButton error={errorObj} onClick={onClose} />\n )}\n <SecondaryButton onClick={() => window.location.reload()}>\n Refresh page\n </SecondaryButton>\n </ActionsContainer>\n\n {details ? (\n <ErrorDetails>\n <ErrorSummary>Full details</ErrorSummary>\n <ErrorStack>{details}</ErrorStack>\n </ErrorDetails>\n ) : error.errorType === \"general\" && error.error ? (\n <ErrorDetails>\n <ErrorSummary>Error details</ErrorSummary>\n <ErrorStack>{error.error}</ErrorStack>\n </ErrorDetails>\n ) : null}\n </InnerModalContent>\n </ModalContent>\n </Dialog.Portal>\n </Dialog.Root>\n );\n}\n","import rootStore from \"../lib/internal-details/lib/root-store.js\";\n\nimport { getEditStore } from \"./get-edit-store.js\";\nimport type {\n CreationContext,\n ParentInfo,\n CreateRequest as EditorTemplateCreateRequest,\n} from \"../lib/internal-details/sb-wrapper.jsx\";\nimport type {\n PropertyInfo,\n SbElement,\n SourceLocation,\n} from \"@superblocksteam/library-shared/types\";\n\nimport type { CreateRequest } from \"@superblocksteam/library-shared/types\";\n\nfunction getParentInfo(parent: SourceLocation): ParentInfo {\n const selectorIds = Array.from(\n getEditStore().runtimeTrackingStore.getSelectorIdsForSourceId(parent.id),\n );\n const parentComponent =\n selectorIds.length > 0\n ? getEditStore().runtimeTrackingStore.getComponent(selectorIds[0])\n : undefined;\n return {\n type: parentComponent?.type,\n };\n}\n\nfunction getComponentBaseProperties(\n componentType: string,\n _parentInfo: ParentInfo,\n editorTemplateCreateRequest?: EditorTemplateCreateRequest<any>,\n) {\n let properties: Record<string, PropertyInfo> = {};\n\n const editorTemplates =\n rootStore.componentRegistry.getEditorTemplates(componentType);\n if (editorTemplates && editorTemplates.length > 1) {\n throw new Error(\n `Multiple editor templates are not supported yet. Found ${editorTemplates.length} for component type: ${componentType}.`,\n );\n }\n\n if (editorTemplateCreateRequest?.properties) {\n properties = {\n ...properties,\n ...(editorTemplateCreateRequest.properties as Record<\n string,\n PropertyInfo\n >),\n };\n }\n\n // TODO(frameworkless): how do we handle dimensions?\n // const safeDimensions = filterSafeStackDimensionProperties({\n // width: width?.value as Dim | undefined,\n // height: height?.value as Dim | undefined,\n // size: size?.value as Dim | undefined | unknown,\n // });\n return {\n properties: {\n ...properties,\n },\n children: editorTemplateCreateRequest?.children ?? [],\n };\n}\n\nfunction getCreateAtParentElement(\n relativeParent: SourceLocation,\n createAt?: \"root\" | \"dropLocation\",\n): { source: SourceLocation } {\n if (createAt === \"root\") {\n const currentSelectors = Array.from(\n getEditStore().runtimeTrackingStore.getSelectorIdsForSourceId(\n relativeParent.id,\n ),\n );\n\n if (currentSelectors.length === 0) {\n throw new Error(`No selector found for parent: ${relativeParent.id}`);\n }\n\n const appSelectorId =\n getEditStore().runtimeTrackingStore.getClosestAncestorByType(\n currentSelectors[0],\n \"App\",\n );\n\n if (!appSelectorId) {\n throw new Error(\n `App component not found for parent: ${relativeParent.id}`,\n );\n }\n\n const appComponent =\n getEditStore().runtimeTrackingStore.getComponent(appSelectorId);\n\n if (!appComponent) {\n throw new Error(`App component not found for selector: ${appSelectorId}`);\n }\n\n return { source: { id: appComponent.sourceId } };\n } else {\n return { source: relativeParent };\n }\n}\n\n// Create components from the Editor\nexport default async function createComponent({\n componentType,\n parent,\n scopeName,\n baseProperties = {},\n skipSecondaryComponentsCreation, // will only create the primary component. Secondary components are usually trigger components (e.g: Button that triggers the modal)\n otherComponentsUpdates,\n}: {\n componentType: string;\n parent: SourceLocation;\n scopeName: string;\n baseProperties?: Record<string, PropertyInfo>;\n skipSecondaryComponentsCreation?: boolean; // e.g. only create modal and not trigger button\n otherComponentsUpdates?: Record<SbElement, Record<string, PropertyInfo>>;\n}): Promise<SbElement | undefined> {\n const parentInfo = getParentInfo(parent);\n\n const editorTemplates =\n rootStore.componentRegistry.getEditorTemplates(componentType);\n if (editorTemplates && editorTemplates.length > 1) {\n throw new Error(\n `Multiple editor templates are not supported yet. Found ${editorTemplates.length} for component type: ${componentType}.`,\n );\n }\n\n const context: CreationContext = {\n parentInfo,\n defaultTagNames: rootStore.componentRegistry.defaultTagNames,\n selfTagName: componentType,\n generateUniqueName: (prefix: string) =>\n `${prefix}-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,\n };\n\n // Creation\n const editorTemplateCreateRequest = editorTemplates?.[0]?.create?.(context);\n\n const primaryEditorTemplateCreateRequest = Array.isArray(\n editorTemplateCreateRequest,\n )\n ? editorTemplateCreateRequest[0]\n : editorTemplateCreateRequest;\n\n if (\n editorTemplateCreateRequest &&\n primaryEditorTemplateCreateRequest?.type !== componentType\n ) {\n throw new Error(\n `When defining a ${Array.isArray(editorTemplateCreateRequest) ? \"multiple\" : \"single\"} component to be created on an EditorTemplate, the type must match with the component being created. got: ${primaryEditorTemplateCreateRequest?.type} when it should have been ${componentType}`,\n );\n }\n\n const editorTemplateCreateRequests = Array.isArray(\n editorTemplateCreateRequest,\n )\n ? editorTemplateCreateRequest\n : [editorTemplateCreateRequest];\n\n const editStore = getEditStore();\n\n function editorTemplateCreateRequestToInternalCreateRequest({\n editorTemplateCreateRequest,\n baseProperties,\n }: {\n editorTemplateCreateRequest?: EditorTemplateCreateRequest<any>;\n baseProperties: Record<string, PropertyInfo>;\n }): CreateRequest {\n const type = editorTemplateCreateRequest?.type ?? componentType;\n\n const { properties: propertiesFromType, children } =\n getComponentBaseProperties(type, parentInfo, editorTemplateCreateRequest);\n\n const properties = {\n ...propertiesFromType,\n ...baseProperties,\n };\n\n const createAtParentElement = getCreateAtParentElement(\n parent,\n editorTemplateCreateRequest?.createAt,\n );\n\n const primaryComponent: CreateRequest = {\n parentElement: createAtParentElement,\n tagName: type,\n properties,\n children,\n scopeName,\n id: editStore.operationManager.generateSourceId(),\n };\n\n return primaryComponent;\n }\n\n const createRequests = editorTemplateCreateRequests.map(\n (editorTemplateCreateRequest, index) =>\n editorTemplateCreateRequestToInternalCreateRequest({\n editorTemplateCreateRequest,\n baseProperties: index === 0 ? baseProperties : {}, // baseProperties are only applied to the primary component\n }),\n );\n\n const hasOtherComponentsUpdates =\n otherComponentsUpdates && Object.keys(otherComponentsUpdates).length > 0;\n\n const hasMultipleCreateComponents =\n editorTemplateCreateRequests.length > 1 && !skipSecondaryComponentsCreation;\n\n const isBatchOperation =\n hasOtherComponentsUpdates || hasMultipleCreateComponents;\n\n if (isBatchOperation) {\n const performOtherComponentsUpdates = (\n otherComponentsUpdates: Record<SbElement, Record<string, PropertyInfo>>,\n ) => {\n Object.entries(otherComponentsUpdates).forEach(([sourceId, updates]) => {\n editStore.operationManager.setWidgetProperties({\n sourceId: sourceId as SbElement,\n properties: updates,\n });\n });\n };\n\n editStore.operationManager.batchUpdate(() => {\n if (skipSecondaryComponentsCreation) {\n editStore.operationManager.createComponent(createRequests[0]);\n } else {\n createRequests.forEach((createRequest) => {\n editStore.operationManager.createComponent(createRequest);\n });\n }\n\n if (hasOtherComponentsUpdates) {\n performOtherComponentsUpdates(otherComponentsUpdates);\n }\n });\n } else {\n editStore.operationManager.createComponent(createRequests[0]);\n }\n\n /**\n * Returns the single id, or the the last component if there are multiple.\n * See EditorTemplate's definition to understand why.\n */\n return createRequests.at(-1)!.id;\n}\n","import { AiContextMode } from \"@superblocksteam/library-shared/types\";\nimport { makeAutoObservable } from \"mobx\";\nimport { editorBridge } from \"../superblocks-editor-bridge.js\";\nimport type RuntimeTrackingStore from \"./runtime-tracking-store.js\";\nimport type {\n RuntimeErrorData,\n SbElement,\n SbSelector,\n} from \"@superblocksteam/library-shared/types\";\n\nexport class AiManager {\n private _isTaggingEnabled = false;\n private _isEditing = false;\n private _editingComponents: SbElement[] = [];\n private _contextMode: AiContextMode = AiContextMode.SILENT;\n private _targetedComponents: SbElement[] = [];\n private _targetedSelectors: SbSelector[] = [];\n private _hasHadSuccessfulBuild = false;\n private _hasEverHadSuccessfulBuild = false;\n\n constructor(private readonly runtimeTrackingStore: RuntimeTrackingStore) {\n makeAutoObservable(this);\n }\n\n getIsTaggingEnabled() {\n return this._isTaggingEnabled;\n }\n\n getIsEditing() {\n return this._isEditing;\n }\n\n getShouldShowLoader() {\n return this._isEditing && !this._hasHadSuccessfulBuild;\n }\n\n setIsTaggingEnabled(isTaggingEnabled: boolean) {\n this._isTaggingEnabled = isTaggingEnabled;\n }\n\n getAiContextMode() {\n return this._contextMode;\n }\n\n shouldToggleComponentInAiContext() {\n return (\n this._isTaggingEnabled && this._contextMode === AiContextMode.AUTO_SELECT\n );\n }\n\n getTargetedComponents() {\n if (this._isTaggingEnabled && this._contextMode !== AiContextMode.SILENT) {\n return this._targetedComponents;\n }\n return [];\n }\n\n getTargetedSelectors() {\n return this._targetedSelectors;\n }\n\n isEditingComponent(id: SbElement) {\n return (\n this._isEditing &&\n this._editingComponents.some((component) => component === id)\n );\n }\n\n isTargetingComponent(id: SbElement) {\n return this._targetedComponents.includes(id);\n }\n\n startEditing() {\n this._isEditing = true;\n const canvasHasRenderableWidgets =\n this.runtimeTrackingStore.hasRenderedNodes();\n\n if (!this._hasEverHadSuccessfulBuild && canvasHasRenderableWidgets) {\n this._hasEverHadSuccessfulBuild = true;\n this._hasHadSuccessfulBuild = true;\n } else {\n this._hasHadSuccessfulBuild = this._hasEverHadSuccessfulBuild;\n }\n\n this.notifyLoaderState();\n }\n\n setEditingComponents(components: SbElement[]) {\n this._editingComponents = components;\n }\n\n finishEditing() {\n this._isEditing = false;\n this._editingComponents = [];\n if (\n !this._hasEverHadSuccessfulBuild &&\n this.runtimeTrackingStore.hasRenderedNodes()\n ) {\n this._hasEverHadSuccessfulBuild = true;\n this._hasHadSuccessfulBuild = true;\n }\n this.notifyLoaderState();\n }\n\n setAiContextMode(\n mode: AiContextMode,\n components?: { id: SbElement; selectorId?: SbSelector }[],\n ) {\n this._contextMode = mode;\n this._targetedComponents =\n components?.map((component) => component.id) ?? [];\n\n if (this._targetedComponents.length > 0) {\n const selectorIds =\n components?.flatMap((component) => {\n if (component.selectorId) {\n return [component.selectorId];\n }\n return Array.from(\n this.runtimeTrackingStore.getSelectorIdsForSourceId(component.id),\n );\n }) ?? [];\n this._targetedSelectors = selectorIds;\n }\n }\n\n addTargetedSelector(selectorId: SbSelector) {\n // when you add a selector, we remove all other selectors for the same source as targets,\n // since visually for the user we only want to show one target\n this.removeAllSharedSelectors(selectorId);\n this._targetedSelectors.push(selectorId);\n }\n\n toggleTargetedSelector(selectorId: SbSelector) {\n if (this._targetedSelectors.includes(selectorId)) {\n this.removeAllSharedSelectors(selectorId);\n } else {\n this.removeAllSharedSelectors(selectorId);\n this._targetedSelectors.push(selectorId);\n }\n }\n\n isTargetedSelector(selectorId: SbSelector) {\n return this._targetedSelectors.includes(selectorId);\n }\n\n /**\n * Returns true if we are targeting a different selector of the same source id, since in some cases we want to keep\n * the same source targeted, but just highlight another selector of it\n */\n isAlternateSourceIdTarget(sourceId: SbElement, selectorId: SbSelector) {\n if (!this.isTargetingComponent(sourceId)) {\n return false;\n }\n\n const allSelectorIds =\n this.runtimeTrackingStore.getSelectorIdsForSourceId(sourceId);\n if (this.isTargetedSelector(selectorId)) {\n return false;\n }\n return allSelectorIds.has(selectorId);\n }\n\n handleRuntimeError(data: RuntimeErrorData) {\n editorBridge.sendRuntimeError(data);\n }\n\n clearRuntimeError(id: string) {\n editorBridge.sendClearRuntimeError(id);\n }\n\n markFirstBuildSuccess() {\n if (this._hasHadSuccessfulBuild) {\n if (!this._hasEverHadSuccessfulBuild) {\n this._hasEverHadSuccessfulBuild = true;\n }\n return;\n }\n\n this._hasHadSuccessfulBuild = true;\n this._hasEverHadSuccessfulBuild = true;\n this.notifyLoaderState();\n }\n\n private notifyLoaderState() {\n editorBridge.sendAiLoaderState?.(this.getShouldShowLoader());\n }\n\n private removeAllSharedSelectors(selectorId: SbSelector) {\n const sourceId = this.runtimeTrackingStore.getSourceId(selectorId);\n if (sourceId) {\n this.removeAllSelectorsForSource(sourceId);\n }\n }\n\n private removeAllSelectorsForSource(sourceId: SbElement) {\n const allSelectorIds =\n this.runtimeTrackingStore.getSelectorIdsForSourceId(sourceId);\n this._targetedSelectors = this._targetedSelectors.filter(\n (selectorId) => !allSelectorIds.has(selectorId),\n );\n }\n}\n","import { makeAutoObservable } from \"mobx\";\n\nexport type ConnectionStatus =\n | \"pre-init\"\n | \"disconnected\"\n | \"connecting\"\n | \"connected\";\n\nclass ConnectionManager {\n connectionStatus: ConnectionStatus = \"pre-init\"; // The status of the connection to the remote dev server\n\n constructor() {\n makeAutoObservable(this);\n }\n\n initializeSocket() {\n this.connectionStatus = \"connecting\";\n }\n\n connect() {\n this.connectionStatus = \"connected\";\n }\n\n disconnect() {\n this.connectionStatus = \"disconnected\";\n }\n}\n\nexport default ConnectionManager;\n","import type { ServerMethods } from \"@superblocksteam/library-shared/types\";\nimport type { ISocketClient } from \"@superblocksteam/shared\";\n\nexport type EditorSocket = ISocketClient<ServerMethods>;\n\nexport class AsyncSocket {\n private socket: EditorSocket | undefined;\n private socketResolvers: ((s: EditorSocket) => void)[] = [];\n\n setSocket(s: EditorSocket) {\n this.socket = s;\n this.socketResolvers.forEach((resolver) => resolver(s));\n this.socketResolvers.length = 0;\n }\n\n clearSocket() {\n this.socket = undefined;\n this.socketResolvers.length = 0;\n }\n\n async waitForSocket(): Promise<EditorSocket> {\n if (this.socket) return this.socket;\n return new Promise((resolve) => this.socketResolvers.push(resolve));\n }\n\n isConnected(): boolean {\n return !!this.socket;\n }\n}\n","import { trace } from \"@opentelemetry/api\";\nimport {\n connectWebSocket,\n createISocketClient,\n ISocketWithClientAuth,\n} from \"@superblocksteam/shared\";\nimport rootStore from \"../lib/internal-details/lib/root-store.js\";\nimport { consoleLogAttributes } from \"../lib/tracing/console-logging.js\";\nimport {\n getContextFromTraceHeaders,\n createIframeSpan,\n} from \"../lib/tracing/context-utils.js\";\nimport { sendNotification } from \"../lib/user-facing/utils/notification.jsx\";\n\nimport { AsyncSocket } from \"./async-socket.js\";\nimport { getEditStore } from \"./get-edit-store.js\";\nimport type {\n ServerMethods,\n LibraryClientMethods,\n} from \"@superblocksteam/library-shared/types\";\nimport type {\n ISocketClient,\n RequestContextBase,\n} from \"@superblocksteam/shared\";\n\nconst PING_INTERVAL_MS = 15_000;\n\ntype OperationApiISocket = ISocketClient<ServerMethods>;\n\nclass OperationAPI {\n private retryAttempts = 0;\n private asyncSocket = new AsyncSocket();\n private isocket: ISocketWithClientAuth<\n LibraryClientMethods,\n ServerMethods,\n RequestContextBase\n > | null = null;\n\n constructor(private readonly serverUrl: string) {}\n\n /**\n * @throws {Error} if the websocket connection can't be initiated after 3 attempts\n */\n async connect({\n peerId,\n userId,\n authorization,\n applicationId,\n traceContext,\n connectionType,\n connectionTarget,\n }: {\n peerId: string;\n userId?: string;\n authorization: string | undefined;\n applicationId: string;\n traceContext?: Record<string, string>;\n connectionType?: \"initial\" | \"reconnect\";\n connectionTarget?: string;\n }) {\n try {\n const result = await connectSocket(this.serverUrl, {\n peerId,\n userId,\n authorization,\n applicationId,\n traceContext,\n connectionType,\n connectionTarget,\n onClose: this.handleSocketClose({\n peerId,\n userId,\n authorization,\n applicationId,\n }),\n });\n if (result?.socket) {\n this.retryAttempts = 0;\n this.asyncSocket.setSocket(result.socket);\n // Store reference to isocket for token updates\n this.isocket = result.isocket;\n } else {\n throw new Error(\"Failed to create socket connection\");\n }\n } catch {\n this.retryAttempts++;\n console.info(\n `App<>Dev box initial connection failed, retrying attempt ${this.retryAttempts}...`,\n );\n // this retry could fail too\n await this.retryConnection({\n peerId,\n userId,\n authorization,\n applicationId,\n });\n }\n }\n\n ensureFilesSynced = async () => {\n try {\n const socket = await this.asyncSocket.waitForSocket();\n await socket.call.editor.ensureFilesSynced();\n } catch (error) {\n console.error(\"Error ensuring files synced\", error);\n }\n };\n\n /**\n * Updates the authorization token for the socket connection.\n * This is called when the token is refreshed in the parent window.\n */\n updateAuthorization(newAuthorization: string | undefined): void {\n if (this.isocket) {\n this.isocket.setAuthorization(newAuthorization);\n console.log(\n \"[internal] [OperationAPI] Updated iframe socket authorization token\",\n );\n } else {\n console.warn(\n \"[internal] [OperationAPI] Cannot update authorization: socket not yet initialized\",\n );\n }\n }\n\n // Happens after initial connection\n private handleSocketClose({\n peerId,\n userId,\n authorization,\n applicationId,\n }: {\n peerId: string;\n userId?: string;\n authorization: string | undefined;\n applicationId: string;\n }) {\n return async (event: CloseEvent) => {\n // Code 1008 is what we use for application ID mismatch\n if (event.code === 1008) {\n sendNotification({\n message: \"Application ID mismatch\",\n description: `You likely switched between multiple tabs. Please refresh the page.`,\n type: \"warning\",\n duration: 10 * 60, // 10 minutes\n });\n rootStore.editStore?.connectionManager.disconnect();\n return; // Don't retry for application ID mismatch\n }\n\n console.info(\n `[internal] [OperationAPI] App<>Dev box Socket closed, retrying attempt ${this.retryAttempts + 1}...`,\n );\n rootStore.editStore?.connectionManager.disconnect();\n\n await this.retryConnection({\n peerId,\n userId,\n authorization,\n applicationId,\n });\n\n if (this.retryAttempts >= 3) {\n this.asyncSocket.clearSocket();\n }\n this.retryAttempts++;\n };\n }\n\n private async retryConnection({\n peerId,\n userId,\n authorization,\n applicationId,\n }: {\n peerId: string;\n userId?: string;\n authorization: string | undefined;\n applicationId: string;\n }) {\n if (this.retryAttempts < 3) {\n await this.connect({ peerId, userId, authorization, applicationId });\n } else {\n console.info(\n `[internal] [OperationAPI] App<>Dev box Socket closed, failed to reconnect after 3 attempts. Throwing error.`,\n );\n throw new Error(\"Failed to reconnect after 3 attempts\");\n }\n }\n}\n\nexport default new OperationAPI(\n typeof window !== \"undefined\" ? window.location.origin : \"\",\n);\n\n// TODO: remove this once we move the heartbeat logic to the WebSocket RPC framework\n/** Returns a function that can be used to stop the heartbeat */\nfunction startSocketHeartbeat(socket: OperationApiISocket) {\n let timeoutId: ReturnType<typeof setTimeout> | undefined;\n let canceled = false;\n (function loop() {\n if (canceled) return;\n timeoutId = setTimeout(async () => {\n try {\n await socket.call.editor.ping();\n console.debug(\"[internal] [OperationAPI] Pinged library socket\");\n } catch (e) {\n console.warn(\"[internal] [OperationAPI] Ping library socket error\", e);\n }\n loop();\n }, PING_INTERVAL_MS);\n })();\n return () => {\n canceled = true;\n clearTimeout(timeoutId);\n };\n}\n\nasync function connectSocket(\n serverUrl: string,\n {\n peerId,\n userId,\n applicationId,\n authorization,\n onClose,\n traceContext,\n connectionType,\n connectionTarget,\n }: {\n peerId: string;\n userId?: string;\n authorization: string | undefined;\n applicationId: string;\n onClose: (event: CloseEvent) => void;\n traceContext?: Record<string, string>;\n connectionType?: \"initial\" | \"reconnect\";\n connectionTarget?: string;\n },\n): Promise<\n | {\n socket: OperationApiISocket;\n isocket: ISocketWithClientAuth<\n LibraryClientMethods,\n ServerMethods,\n RequestContextBase\n >;\n }\n | undefined\n> {\n if (!serverUrl) {\n return undefined;\n }\n\n const wsUrl = new URL(\"/sb-updates\", serverUrl);\n wsUrl.searchParams.set(\"peerId\", peerId);\n if (userId) {\n wsUrl.searchParams.set(\"userId\", userId);\n }\n wsUrl.searchParams.set(\"applicationId\", applicationId);\n\n rootStore.editStore?.connectionManager.initializeSocket();\n\n // Extract parent context from trace headers if provided\n let parentContext;\n if (traceContext) {\n parentContext = getContextFromTraceHeaders(traceContext);\n }\n\n // Create child span for app websocket connection\n const appWebsocketSpan = createIframeSpan(\n \"devServerAppWebSocketConnection\",\n {\n url: wsUrl.toString(),\n connection_source: \"app\",\n connection_type: connectionType || \"initial\",\n connection_target: connectionTarget || \"default\",\n application_id: applicationId,\n },\n parentContext,\n );\n\n const wsStartTime = Date.now();\n console.log(\n \"[internal] [OperationAPI] Dev server connection app websocket starting\",\n consoleLogAttributes({\n url: wsUrl.toString(),\n connectionSource: \"app\",\n connectionType: connectionType || \"initial\",\n connectionTarget: connectionTarget || \"default\",\n }),\n );\n\n try {\n let stopSocketHeartbeat: (() => void) | undefined;\n const ws = await connectWebSocket(wsUrl.toString());\n const isocket = new ISocketWithClientAuth<\n LibraryClientMethods,\n ServerMethods,\n RequestContextBase\n >(\n ws,\n authorization,\n {\n nonVisualEdit: [\n async () => {\n getEditStore().ui.selectWidget(null); // this also sends a postMessage to parent\n },\n ],\n renameRegisteredComponent: [\n async (payload) => {\n // TODO: do we need a better way to track components?\n const { name, oldName } = payload;\n if (oldName) {\n rootStore.componentRegistry.renameComponent(oldName, name);\n }\n },\n ],\n removeRegisteredComponent: [\n async (payload) => {\n // TODO: do we need a better way to track components?\n rootStore.componentRegistry.deleteComponent(payload.name);\n },\n ],\n deleteEntities: [\n async (_payload) => {\n // no-op\n },\n ],\n clientImport: [\n async (payload) => {\n const { importPath } = payload;\n try {\n await import(/* @vite-ignore */ `${importPath}?v=${Date.now()}`);\n return undefined;\n } catch (error) {\n const err = error as Error;\n return {\n message: err.message,\n stack: err.stack,\n name: err.name,\n };\n }\n },\n ],\n },\n [],\n trace.getTracer(\"superblocks-ui-framework\"),\n {\n onClose: (event) => {\n stopSocketHeartbeat?.();\n stopSocketHeartbeat = undefined;\n onClose(event as unknown as CloseEvent);\n console.log(\n \"[internal] [OperationAPI] Dev server connection app websocket closed\",\n consoleLogAttributes({\n connectionSource: \"app\",\n connectionType: connectionType || \"initial\",\n connectionTarget: connectionTarget || \"default\",\n }),\n );\n rootStore.editStore?.connectionManager.disconnect();\n },\n\n timeouts: {\n connectionTimeoutInSeconds: undefined,\n noResponseTimeoutInSeconds: 60,\n },\n },\n );\n const socket = createISocketClient<\n ServerMethods,\n LibraryClientMethods,\n RequestContextBase\n >(isocket);\n\n const wsEndTime = Date.now();\n const wsDuration = wsEndTime - wsStartTime;\n console.log(\n \"[internal] [OperationAPI] Dev server connection app websocket succeeded\",\n consoleLogAttributes({\n connectionSource: \"app\",\n connectionType: connectionType || \"initial\",\n connectionTarget: connectionTarget || \"default\",\n durationMs: wsDuration,\n }),\n );\n\n // Send connection success to parent for metrics recording\n window.parent.postMessage(\n {\n type: \"app-websocket-connected\",\n payload: {\n success: true,\n durationMs: wsDuration,\n },\n },\n \"*\",\n );\n\n // End span on success\n appWebsocketSpan.end();\n\n stopSocketHeartbeat = startSocketHeartbeat(socket);\n rootStore.editStore?.connectionManager.connect();\n return { socket, isocket };\n } catch (error) {\n const wsEndTime = Date.now();\n const wsDuration = wsEndTime - wsStartTime;\n console.error(\n \"[internal] [OperationAPI] Dev server connection app websocket failed\",\n consoleLogAttributes({\n connectionSource: \"app\",\n connectionType: connectionType || \"initial\",\n connectionTarget: connectionTarget || \"default\",\n durationMs: wsDuration,\n error: error instanceof Error ? error.message : String(error),\n }),\n );\n\n // Send connection failure to parent for metrics recording\n window.parent.postMessage(\n {\n type: \"app-websocket-connected\",\n payload: {\n success: false,\n durationMs: wsDuration,\n error: {\n message: error instanceof Error ? error.message : String(error),\n type: error instanceof Error ? error.constructor.name : \"Unknown\",\n stack: error instanceof Error ? error.stack : undefined,\n },\n },\n },\n \"*\",\n );\n\n // End span with error\n if (error instanceof Error) {\n appWebsocketSpan.recordException(error);\n }\n appWebsocketSpan.end();\n\n rootStore.editStore?.connectionManager.disconnect();\n throw error;\n }\n}\n","// https://github.com/microsoft/TypeScript/issues/47663#issuecomment-1519138189\n// this is for superblocksSlice, import immer\n\nimport { generateSourceId } from \"@superblocksteam/library-shared\";\nimport { action, makeAutoObservable } from \"mobx\";\nimport { generateId } from \"../../lib/utils/generate-id.js\";\nimport SourceUpdateApi from \"../source-update-api.js\";\n\nimport { editorBridge } from \"../superblocks-editor-bridge.js\";\nimport type {\n BatchUpdateRequest,\n CreateRequest,\n DeleteRequest,\n EditOperationPayload,\n EditOperations,\n EditOperationType,\n PropertyInfo,\n ReparentRequest,\n SbElement,\n SetPropertiesRequest,\n SetPropertyRequest,\n SourceLocation,\n} from \"@superblocksteam/library-shared/types\";\n\ntype OptimisticOperation<P> = {\n type: keyof EditOperations;\n payload: P;\n id: string;\n callback?: () => void; // called when the operation is cleared by a hot reload\n};\n\nexport type ReparentTransaction = OptimisticOperation<ReparentRequest>;\ntype SetPropertiesTransaction = OptimisticOperation<SetPropertiesRequest>;\ntype SetPropertyTransaction = OptimisticOperation<SetPropertyRequest>;\ntype CreateComponentTransaction = OptimisticOperation<CreateRequest>;\ntype DeleteComponentsTransaction = OptimisticOperation<DeleteRequest>;\n\ntype PendingTransaction =\n | ReparentTransaction\n | SetPropertiesTransaction\n | SetPropertyTransaction\n | CreateComponentTransaction\n | DeleteComponentsTransaction;\n\nclass OperationManager {\n private pendingTransactions: Array<PendingTransaction> = [];\n\n private waitingForBatch: boolean = false;\n private batchOperations: Array<PendingTransaction> = [];\n private batchOperationTransactionId: string | undefined;\n\n visibleSourceIds: string[] = [];\n\n constructor() {\n makeAutoObservable(this);\n }\n\n get allPendingTransactions() {\n return this.pendingTransactions;\n }\n\n get pendingReparentOperations() {\n return this.pendingTransactions.filter(\n (t) => t.type === \"editor:moveComponent\",\n ) as ReparentTransaction[];\n }\n\n get pendingDeleteOperations() {\n return this.pendingTransactions.filter(\n (t) => t.type === \"editor:deleteComponents\",\n ) as DeleteComponentsTransaction[];\n }\n\n get pendingSetPropertiesOperations() {\n return this.pendingTransactions.filter(\n (t) => t.type === \"editor:setProperties\",\n ) as SetPropertiesTransaction[];\n }\n\n get hasPendingOperations() {\n return this.pendingTransactions.length > 0;\n }\n\n get allNames() {\n return [];\n }\n\n @action\n private executeOrAddToBatch(\n operation: Omit<OptimisticOperation<PendingTransaction[\"payload\"]>, \"id\">,\n addTransaction: boolean = true,\n ) {\n const transactionId = this.batchOperationTransactionId ?? generateId();\n\n const payload = this.waitingForBatch\n ? operation.payload\n : {\n ...operation.payload,\n transaction: {\n id: transactionId,\n origin: \"LIBRARY\",\n },\n };\n\n const opWithId = {\n ...operation,\n id: transactionId,\n payload,\n } as PendingTransaction;\n\n if (addTransaction) {\n this.addPendingTransaction(opWithId);\n }\n\n if (this.waitingForBatch) {\n this.batchOperations.push(opWithId);\n } else {\n switch (operation.type) {\n case \"editor:moveComponent\":\n return editorBridge.editOpRequest(\n \"editor:moveComponent\",\n payload as ReparentRequest,\n );\n case \"editor:setProperties\":\n return editorBridge.editOpRequest(\n \"editor:setProperties\",\n payload as SetPropertiesRequest,\n );\n case \"editor:createComponent\":\n return editorBridge.editOpRequest(\n \"editor:createComponent\",\n payload as CreateRequest,\n );\n case \"editor:deleteComponents\":\n return editorBridge.editOpRequest(\n \"editor:deleteComponents\",\n payload as DeleteRequest,\n );\n }\n }\n }\n\n @action\n private addPendingTransaction(transaction: PendingTransaction) {\n // TODO(alex): good luck!\n // if (transaction.type === \"editor:createComponent\") {\n // getEditStore().runtimeTrackingStore.addOptimisticCreateWidget(\n // transaction.payload as CreateRequest,\n // );\n // }\n this.pendingTransactions.push(transaction);\n }\n\n @action\n clearPendingTransactions(transactionIds: string[]) {\n const toClear = new Set(transactionIds);\n const { cleared, remaining } = this.pendingTransactions.reduce(\n (acc, transaction) => {\n if (toClear.has(transaction.id)) {\n acc.cleared.push(transaction);\n } else {\n acc.remaining.push(transaction);\n }\n return acc;\n },\n {\n cleared: [] as PendingTransaction[],\n remaining: [] as PendingTransaction[],\n },\n );\n\n this.pendingTransactions = remaining;\n\n // Execute callbacks for cleared transactions\n cleared.forEach((transaction) => {\n if (transaction.callback) {\n transaction.callback();\n }\n });\n }\n\n @action\n batchUpdate(performOperations: () => void) {\n this.waitingForBatch = true;\n this.batchOperationTransactionId = generateId();\n performOperations();\n\n editorBridge.editOpRequest(\"editor:batchUpdate\", {\n updates: this.batchOperations.map(\n (op) =>\n ({\n type: op.type,\n payload: op.payload,\n }) as BatchUpdateRequest[\"updates\"][number],\n ),\n transaction: {\n origin: \"LIBRARY\",\n id: this.batchOperationTransactionId,\n },\n });\n\n this.waitingForBatch = false;\n this.batchOperations = [];\n this.batchOperationTransactionId = undefined;\n }\n\n @action\n createComponent(payload: CreateRequest) {\n this.executeOrAddToBatch({\n type: \"editor:createComponent\",\n payload,\n });\n }\n\n @action\n dropComponent(action: {\n from: { source: SourceLocation };\n to: { source: SourceLocation };\n propsToChange?: Record<string, PropertyInfo>;\n }) {\n const { from, to, propsToChange } = action;\n\n const payload: ReparentRequest = {\n from,\n to,\n changedProps: propsToChange ?? {},\n };\n this.executeOrAddToBatch({\n type: \"editor:moveComponent\",\n payload,\n });\n }\n\n @action\n deleteComponents(sourceIds: SbElement[]) {\n const payload: DeleteRequest = {\n elements: sourceIds.map((sourceId) => ({\n source: { id: sourceId },\n })),\n };\n\n this.executeOrAddToBatch(\n {\n type: \"editor:deleteComponents\",\n payload,\n },\n // TODO(alex): not sure if we need this boolean?\n false,\n );\n }\n\n acknowledgeEditOperation(operation: EditOperationPayload<EditOperationType>) {\n if (\n !(\"transaction\" in operation.payload) ||\n !operation.payload.transaction?.id\n ) {\n console.error(\"No transaction id in edit operation\", operation);\n return;\n }\n\n const addOperation = (\n operation: EditOperationPayload<EditOperationType>,\n batchTransactionId?: string,\n ) => {\n switch (operation.type) {\n case \"editor:createComponent\": {\n const { type, payload } =\n operation as EditOperationPayload<\"editor:createComponent\">;\n this.addPendingTransaction({\n type,\n id: batchTransactionId ?? payload.transaction!.id,\n payload,\n });\n break;\n }\n case \"editor:deleteComponents\": {\n const { type, payload } =\n operation as EditOperationPayload<\"editor:deleteComponents\">;\n this.addPendingTransaction({\n type,\n id: batchTransactionId ?? payload.transaction!.id,\n payload,\n });\n break;\n }\n case \"editor:moveComponent\": {\n const { type, payload } =\n operation as EditOperationPayload<\"editor:moveComponent\">;\n this.addPendingTransaction({\n type,\n id: batchTransactionId ?? payload.transaction!.id,\n payload,\n });\n break;\n }\n case \"editor:setProperties\": {\n const { type, payload } =\n operation as EditOperationPayload<\"editor:setProperties\">;\n this.addPendingTransaction({\n type,\n id: payload.transaction!.id,\n payload,\n });\n break;\n }\n case \"editor:deleteProperties\": {\n const { payload } =\n operation as EditOperationPayload<\"editor:deleteProperties\">;\n // we can write the deleteProperties as a setProperties\n const asSetProperties: SetPropertiesRequest = {\n element: {\n source: {\n id: payload.element.source.id,\n },\n },\n properties: Object.fromEntries(\n payload.properties.map((p) => [\n p,\n {\n type: \"STATIC\",\n value: undefined,\n __info: true,\n },\n ]),\n ),\n };\n this.addPendingTransaction({\n type: \"editor:setProperties\",\n id: batchTransactionId ?? payload.transaction!.id,\n payload: asSetProperties,\n });\n break;\n }\n default:\n console.error(\"Unknown edit operation\", operation);\n }\n };\n\n if (operation.type === \"editor:batchUpdate\") {\n const { payload } =\n operation as EditOperationPayload<\"editor:batchUpdate\">;\n if (!payload.transaction?.id) {\n console.error(\"No transaction id in batch\", operation);\n return;\n }\n for (const update of payload.updates) {\n addOperation(update, payload.transaction.id);\n }\n } else {\n addOperation(operation);\n }\n }\n\n @action\n writeRuntimeProperties(\n sourceId: SbElement,\n transactionId: string,\n updates: Record<string, PropertyInfo<unknown>>,\n ) {\n // this can't be part of batch because it came from the editor\n this.addPendingTransaction({\n type: \"editor:setProperties\",\n id: transactionId,\n payload: { element: { source: { id: sourceId } }, properties: updates },\n });\n }\n\n @action\n setWidgetProperties({\n sourceId,\n properties,\n callback,\n }: {\n sourceId: SbElement;\n properties: Record<string, PropertyInfo<unknown>>;\n callback?: () => void;\n }) {\n const payload: SetPropertiesRequest = {\n element: {\n source: {\n id: sourceId,\n },\n },\n properties,\n };\n\n this.executeOrAddToBatch({\n type: \"editor:setProperties\",\n payload,\n callback,\n });\n }\n\n @action\n setWidgetProperty({\n sourceId,\n property,\n value,\n callback,\n }: {\n sourceId: SbElement;\n property: string;\n value: PropertyInfo<unknown>;\n callback?: () => void;\n }) {\n this.setWidgetProperties({\n sourceId,\n properties: { [property]: value },\n callback,\n });\n }\n\n async ensureFilesSynced() {\n await SourceUpdateApi.ensureFilesSynced();\n }\n\n generateSourceId() {\n return generateSourceId();\n }\n}\n\nexport default OperationManager;\n","import {\n ViteMessageKind,\n type PropertyInfo,\n type SbElement,\n} from \"@superblocksteam/library-shared/types\";\nimport { autorun, makeAutoObservable } from \"mobx\";\nimport { createPropertiesPanelDefinition } from \"../../lib/user-facing/properties-panel/properties-panel-definition.js\";\nimport { editorBridge } from \"../superblocks-editor-bridge.js\";\nimport type { ComponentRegistry } from \"../../lib/internal-details/lib/features/component-registry.js\";\nimport type {\n Prop,\n PropertiesDefinition,\n} from \"../../lib/user-facing/properties-panel/props-builder.js\";\nimport type { EditStore } from \"../edit-store.js\";\nimport type { PropertiesPanelDefinition } from \"@superblocksteam/library-shared/props\";\nimport type { SbSelector } from \"@superblocksteam/library-shared/types\";\nimport type { IReactionDisposer } from \"mobx\";\n\nclass PropertiesPanelManager {\n private propertiesDefinitions = new Map<string, PropertiesDefinition>();\n private propertiesPanelTrackerDisposer: IReactionDisposer | null = null;\n\n private _propertyLookupCache = new Map<\n string,\n Record<string, Prop<any, any>>\n >();\n\n private removeHotReloadListener: (() => void) | null = null;\n\n constructor(\n readonly editStore: EditStore,\n readonly componentsManager: ComponentRegistry,\n ) {\n makeAutoObservable<PropertiesPanelManager, \"_propertyLookupCache\">(this, {\n _propertyLookupCache: false,\n });\n\n this.attachHotReloadListener();\n }\n\n getPropertiesPanel(selectorId: SbSelector): PropertiesPanelDefinition {\n const component =\n this.editStore.runtimeTrackingStore.getComponent(selectorId);\n const props = component?.props;\n\n if (!component?.type) {\n return { sections: [] };\n }\n\n const componentType = component.displayName || component.type;\n\n if (!componentType) {\n return { sections: [] };\n }\n\n const propertiesDefinition = this.propertiesDefinitions.get(componentType);\n if (!propertiesDefinition) {\n return { sections: [] };\n }\n\n return createPropertiesPanelDefinition(propertiesDefinition, props ?? {});\n }\n\n trackPropertiesPanel(selectorId: SbSelector) {\n if (this.propertiesPanelTrackerDisposer) {\n this.propertiesPanelTrackerDisposer();\n }\n const sourceId =\n this.editStore.runtimeTrackingStore.getSourceId(selectorId);\n if (!sourceId) {\n return;\n }\n this.propertiesPanelTrackerDisposer = autorun(\n () => {\n const propertiesPanel = this.getPropertiesPanel(selectorId);\n editorBridge.addPropertiesPanel(sourceId, propertiesPanel);\n },\n {\n name: `trackPropertiesPanel[${selectorId}]`,\n },\n );\n }\n\n untrackPropertiesPanel() {\n this.propertiesPanelTrackerDisposer?.();\n this.propertiesPanelTrackerDisposer = null;\n }\n\n getPropertiesDefinition(type: string): PropertiesDefinition | undefined {\n return this.propertiesDefinitions.get(type);\n }\n\n setPropertiesDefinition(\n widgetType: string,\n propertiesDefinition: PropertiesDefinition,\n ) {\n this.propertiesDefinitions.set(widgetType, propertiesDefinition);\n }\n\n updatePropertiesDefinitionForType(type: string) {\n // No-op: Hot reload triggers re-registration which calls setPropertiesDefinition\n // This method is kept for backward compatibility with hot reload messages\n console.log(\"[internal] [NOOP] updatePropertiesDefinitionForType: \", type);\n }\n\n computeAndApplySideEffectsForPropertyUpdate(payload: {\n sourceId: SbElement;\n updates: Record<string, PropertyInfo<unknown>>;\n }): Record<SbElement, Record<string, PropertyInfo<unknown>>> {\n console.log(\n \"[internal] [NOOP] computeAndApplySideEffectsForPropertyUpdate\",\n );\n return {\n [payload.sourceId]: payload.updates,\n };\n }\n\n /**\n * When a custom component's source code is updated, we want to update the properties definition for that component.\n * In order to do that, we need to listen to vite's hot reload events. We can't put import.meta.hot calls in the library\n * because Vite just compiled all of those out in library builds, so we inject a listener from the plugin instead.\n * https://github.com/vitejs/vite/blob/v6.2/packages/vite/src/node/plugins/define.ts#L37\n */\n private attachHotReloadListener() {\n this.removeHotReloadListener?.();\n\n this.removeHotReloadListener = this.editStore.onViteMessage(\n ViteMessageKind.UPDATE_CUSTOM_COMPONENT,\n (message) => {\n this.updatePropertiesDefinitionForType(message.component);\n },\n );\n }\n}\n\nexport default PropertiesPanelManager;\n","/* eslint-disable @typescript-eslint/no-unsafe-declaration-merging */\nimport { Graph } from \"@dagrejs/graphlib\";\nimport { action, makeObservable, observable } from \"mobx\";\nimport type { Edge, GraphOptions } from \"@dagrejs/graphlib\";\n\n// Generic type parameters are used in the interface below via declaration merging\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport class ObservableGraph<NL = any, EL = any> extends Graph {\n constructor(args: GraphOptions) {\n super(args);\n\n makeObservable<any>(this, {\n // Core graph properties\n _label: observable,\n _defaultNodeLabelFn: observable,\n _defaultEdgeLabelFn: observable,\n\n // Node storage\n _nodes: observable,\n _nodeCount: observable,\n\n // Edge storage\n _in: observable,\n _preds: observable,\n _out: observable,\n _sucs: observable,\n _edgeObjs: observable,\n _edgeLabels: observable,\n _edgeCount: observable,\n\n // Compound graph properties (conditionally set)\n ...(args.compound\n ? {\n _parent: observable,\n _children: observable,\n }\n : {}),\n\n // Mutation methods (actions)\n setGraph: action,\n setDefaultNodeLabel: action,\n setNode: action,\n setNodes: action,\n removeNode: action,\n setParent: action,\n setDefaultEdgeLabel: action,\n setEdge: action,\n setPath: action,\n removeEdge: action,\n });\n }\n}\n\n// Use interface declaration merging to add type-safe method signatures\nexport interface ObservableGraph<NL = any, EL = any> {\n // Node operations\n setNode(name: string, label?: NL): this;\n node(name: string): NL;\n setDefaultNodeLabel(label: NL): this;\n setDefaultNodeLabel(labelFn: (v: string) => NL): this;\n\n // Edge operations\n setEdge(v: string, w: string, label?: EL, name?: string): this;\n setEdge(edge: Edge, label?: EL): this;\n edge(v: string, w: string, name?: string): EL;\n edge(edge: Edge): EL;\n setDefaultEdgeLabel(label: EL): this;\n setDefaultEdgeLabel(\n labelFn: (v: string, w: string, name?: string) => EL,\n ): this;\n setPath(vs: string[], label?: EL): this;\n}\n","import { SELECTOR_ID_ATTRIBUTE } from \"@superblocksteam/library-shared\";\nimport { makeAutoObservable, observable } from \"mobx\";\nimport type { ComponentNode, ITrackingStore } from \"./types\";\nimport type {\n SbElement,\n SbSelector,\n} from \"@superblocksteam/library-shared/types\";\n\nexport class RuntimeComponentNode implements ComponentNode {\n private readonly store: ITrackingStore;\n public readonly selectorId: SbSelector;\n public readonly sourceId: SbElement;\n public readonly type: any;\n public readonly isSbComponent: boolean;\n public readonly isHtmlElement: boolean;\n public readonly noSelect?: boolean;\n\n public props?: Record<string, unknown>;\n constructor(\n store: ITrackingStore,\n params: {\n selectorId: SbSelector;\n sourceId: SbElement;\n type: any;\n isSbComponent: boolean;\n isHtmlElement: boolean;\n noSelect?: boolean;\n },\n ) {\n this.store = store;\n this.sourceId = params.sourceId;\n this.selectorId = params.selectorId;\n this.type = params.type;\n this.isSbComponent = params.isSbComponent;\n this.isHtmlElement = params.isHtmlElement;\n this.noSelect = params.noSelect;\n makeAutoObservable<RuntimeComponentNode>(this, {\n type: observable.ref,\n props: observable.ref,\n });\n }\n\n get firstRenderedTag() {\n if (this?.isHtmlElement) {\n return this.selectorId;\n }\n\n const element = document.querySelector(\n `[${SELECTOR_ID_ATTRIBUTE}=\"${this.selectorId}\"]`,\n );\n if (element) {\n return this.selectorId;\n }\n\n const children = this.store.graph.children(this.selectorId) ?? [];\n for (const child of children) {\n const childComponent = this.store.jsxNodes[child as SbSelector];\n const result = childComponent?.firstRenderedTag;\n if (result) {\n return result;\n }\n }\n return undefined;\n }\n\n get nearestSelectableAncestor() {\n // valid situations where I am the nearest registered ancestor:\n // - I am a registered REACT component (not an html element)\n // - I am a registered html element and I have no data-no-select attribute\n if (this.isSbComponent && !this.noSelect) {\n return this.selectorId;\n }\n const componentParent = this.store.graph.parent(this.selectorId) as\n | SbSelector\n | undefined;\n if (componentParent) {\n return this.store.jsxNodes[componentParent]?.nearestSelectableAncestor;\n }\n return undefined;\n }\n\n get displayName() {\n if (this.isHtmlElement) {\n return this.type;\n }\n\n return getTypeString(this.type);\n }\n}\n\nfunction getTypeString(type: any) {\n if (typeof type === \"string\") {\n return type;\n }\n return type.displayName || type.name || \"Component\";\n}\n","import { makeAutoObservable } from \"mobx\";\nimport { ObservableGraph } from \"../runtime-graph/observable-graph.js\";\nimport { RuntimeComponentNode } from \"../runtime-graph/runtime-component-node.js\";\nimport type { EditStore } from \"../edit-store.js\";\nimport type {\n NodeLabel,\n EdgeType,\n ComponentNode,\n SourceCodeNode,\n} from \"../runtime-graph/types.js\";\nimport type {\n SbElement,\n SbSelector,\n} from \"@superblocksteam/library-shared/types\";\n\nclass RuntimeTrackingStore {\n // Is reference to edit store needed?\n constructor(readonly editStore: EditStore | undefined) {\n makeAutoObservable<RuntimeTrackingStore>(this);\n }\n\n private graph = new ObservableGraph<NodeLabel, EdgeType>({\n directed: true,\n multigraph: true,\n compound: true,\n });\n\n // Store component metadata separately from graph nodes\n private jsxNodes: Partial<Record<SbSelector, ComponentNode>> = {};\n private sourceNodes: Partial<Record<SbElement, SourceCodeNode>> = {};\n\n private disabledComponents = new Set<SbSelector>();\n\n public registerComponent(\n selectorId: SbSelector,\n params: {\n sourceId: SbElement;\n type: any;\n parentSelectorId?: SbSelector;\n isSbComponent: boolean;\n isHtmlElement: boolean;\n noSelect?: boolean;\n },\n ) {\n // jsx metadata\n const componentNode = new RuntimeComponentNode(\n {\n jsxNodes: this.jsxNodes,\n graph: this.graph,\n },\n {\n selectorId,\n sourceId: params.sourceId,\n type: params.type,\n isSbComponent: params.isSbComponent,\n isHtmlElement: params.isHtmlElement,\n noSelect: params.noSelect,\n },\n );\n this.jsxNodes[selectorId] = componentNode;\n\n this.graph.setNode(selectorId, {\n id: selectorId,\n type: \"JSX\",\n } satisfies NodeLabel);\n\n // Set parent-child relationship using compound graph\n if (params.parentSelectorId) {\n if (!this.graph.hasNode(params.parentSelectorId)) {\n this.graph.setNode(params.parentSelectorId, {\n id: params.parentSelectorId,\n type: \"JSX\",\n } satisfies NodeLabel);\n }\n this.graph.setParent(selectorId, params.parentSelectorId);\n }\n\n // source metadata\n const sourceNode: SourceCodeNode = {\n sourceId: params.sourceId,\n };\n this.sourceNodes[params.sourceId] = sourceNode;\n this.graph.setNode(params.sourceId, {\n id: params.sourceId,\n type: \"SOURCE\",\n } satisfies NodeLabel);\n\n // connect jsx node to source node\n this.graph.setEdge(params.sourceId, selectorId, undefined, \"SOURCE_TO_JSX\");\n }\n\n public getDisplayName(selectorId: SbSelector) {\n return this.jsxNodes[selectorId]?.displayName ?? \"Component\";\n }\n\n public unregisterComponent(selectorId: SbSelector) {\n this.graph.removeNode(selectorId);\n\n // allow these to be GC'd\n delete this.jsxNodes[selectorId];\n\n this.disabledComponents.delete(selectorId);\n }\n\n public getFirstAnchorableTag(selectorId: SbSelector): SbSelector | undefined {\n const firstRenderedTag = this.jsxNodes[selectorId]?.firstRenderedTag;\n return firstRenderedTag;\n }\n\n public getNearestSelectableAncestor(\n selectorId: SbSelector,\n skipSelf: boolean = false,\n ): SbSelector | undefined {\n if (skipSelf) {\n const componentParent = this.graph.parent(selectorId) as\n | SbSelector\n | undefined;\n if (componentParent) {\n return this.jsxNodes[componentParent]?.nearestSelectableAncestor;\n }\n return undefined;\n }\n return this.jsxNodes[selectorId]?.nearestSelectableAncestor;\n }\n\n public updatePropsForComponent(\n selectorId: SbSelector,\n props: Record<string, unknown>,\n ) {\n const componentNode = this.jsxNodes[selectorId];\n if (componentNode) {\n componentNode.props = props;\n\n if (props.disabled) {\n this.disabledComponents.add(selectorId);\n } else {\n this.disabledComponents.delete(selectorId);\n }\n }\n }\n\n public getComponent(selectorId: SbSelector) {\n return this.jsxNodes[selectorId];\n }\n\n public getComponentParent(selectorId: SbSelector): SbSelector {\n return this.graph.parent(selectorId) as SbSelector;\n }\n\n public getComponentChildren(selectorId: SbSelector): SbSelector[] {\n return (this.graph.children(selectorId) as SbSelector[]) || [];\n }\n\n public getSelectorIdsForSourceId(sourceId: SbElement): Set<SbSelector> {\n const sourceNode = this.sourceNodes[sourceId];\n if (!sourceNode) {\n return new Set();\n }\n const sourceNodeEdges = this.graph.outEdges(sourceId) ?? [];\n return new Set(\n sourceNodeEdges\n .filter((edge) => {\n return edge.name === \"SOURCE_TO_JSX\";\n })\n .map((edge) => edge.w as SbSelector),\n );\n }\n\n public getSourceId(selectorId: SbSelector): SbElement | undefined {\n return this.jsxNodes[selectorId]?.sourceId;\n }\n\n public getClosestAncestorByType(\n selectorId: SbSelector,\n type: string,\n ): SbSelector | undefined {\n let current: SbSelector | undefined = selectorId;\n while (current) {\n const component = this.jsxNodes[current];\n if (component?.type === type) return current;\n current = this.graph.parent(current) as SbSelector | undefined;\n }\n return undefined;\n }\n\n public hasRenderedNodes(): boolean {\n return Object.keys(this.jsxNodes).length > 0;\n }\n\n public getDisabledComponents(): SbSelector[] {\n return Array.from(this.disabledComponents);\n }\n\n /**\n * Given a selectorId that represents a DOM element, walks up the component tree\n * to find the outermost registered component whose firstRenderedTag matches this selectorId.\n * This is used to select the component when clicking on its root DOM element.\n *\n * IMPORTANT: This only returns a component if the anchorSelectorId is the IMMEDIATE parent\n * of the component (i.e., the component doesn't have any intermediate nodes between itself\n * and the anchor). This prevents inner HTML elements from being treated as component roots.\n *\n * ONLY returns registered components (isSbComponent: true). Unregistered wrapper components\n * are treated as transparent and skipped.\n *\n * Returns undefined if no registered component has this as its firstRenderedTag.\n */\n public getOutermostComponentForFirstRenderedTag(\n anchorSelectorId: SbSelector,\n ): SbSelector | undefined {\n // First check: is the anchor itself a registered component?\n const anchorComponent = this.jsxNodes[anchorSelectorId];\n if (\n anchorComponent &&\n !anchorComponent.isHtmlElement &&\n anchorComponent.isSbComponent\n ) {\n // The clicked element itself is a registered component\n return anchorSelectorId;\n }\n\n // Second check: walk up to find registered components whose DIRECT firstRenderedTag\n // is this anchor (meaning there are no intermediate HTML elements)\n // ONLY collect registered components (isSbComponent: true)\n const registeredMatches: SbSelector[] = [];\n let current: SbSelector | undefined = this.graph.parent(\n anchorSelectorId,\n ) as SbSelector | undefined;\n\n while (current) {\n const component = this.jsxNodes[current];\n if (!component) {\n break;\n }\n\n // Check if this is a REGISTERED component (not an HTML element, and isSbComponent is true)\n // whose firstRenderedTag directly matches our anchor\n if (\n !component.isHtmlElement &&\n component.isSbComponent &&\n component.firstRenderedTag === anchorSelectorId\n ) {\n registeredMatches.push(current);\n }\n\n // Walk up to parent\n current = this.graph.parent(current) as SbSelector | undefined;\n }\n\n // Return the outermost registered component, or undefined if none found\n return registeredMatches.length > 0\n ? registeredMatches[registeredMatches.length - 1]\n : undefined;\n }\n}\n\nexport default RuntimeTrackingStore;\n","import { Property, Dim } from \"@superblocksteam/library-shared\";\nimport { makeAutoObservable } from \"mobx\";\nimport { startEditorSync } from \"../mobx-sync/mobx-editor-sync.js\";\nimport type { RootStore } from \"../../lib/internal-details/lib/root-store.js\";\nimport type { PropertyInfo } from \"@superblocksteam/library-shared\";\nimport type {\n SbElement,\n SbSelector,\n} from \"@superblocksteam/library-shared/types\";\n\ntype ResizeState = {\n selectorId: SbSelector;\n sourceId: SbElement;\n dragStartX: number;\n dragStartY: number;\n start: {\n width: number;\n height: number;\n };\n resizedPosition: string;\n widthToUpdate: Dim | null;\n heightToUpdate: Dim | null;\n isApplyingResize: boolean;\n};\n\nexport class ResizingManager {\n private _activeResizes: Map<SbElement, ResizeState> = new Map();\n\n constructor(private root: RootStore) {\n makeAutoObservable(this);\n\n startEditorSync({\n store: this,\n storeId: \"resizing\",\n projection(store) {\n const resize = store.activeResize;\n return {\n isResizing: resize != null,\n activeResize: resize\n ? {\n width: resize.widthToUpdate,\n height: resize.heightToUpdate,\n }\n : null,\n };\n },\n });\n }\n\n get activeResize() {\n const selectedSourceId = this.root.editStore?.ui.getSelectedSourceIds()[0];\n if (!selectedSourceId) {\n return null;\n }\n return this._activeResizes.get(selectedSourceId);\n }\n\n private isLockedAspectRatio(selectorId: SbSelector) {\n const component =\n this.root.editStore?.runtimeTrackingStore.getComponent(selectorId);\n\n const editorConfig = component?.type\n ? this.root.componentRegistry.getEditorConfig(component?.type)\n : null;\n return editorConfig?.isFixedAspectRatio === true;\n }\n\n public startResizing(\n dragStartX: number,\n dragStartY: number,\n selectorId: SbSelector,\n position: string,\n ) {\n const component =\n this.root.editStore?.runtimeTrackingStore.getComponent(selectorId);\n if (!component) {\n console.error(`Could not find component ${selectorId}`);\n return;\n }\n\n this._activeResizes.set(component.sourceId, {\n selectorId,\n sourceId: component.sourceId,\n dragStartX,\n dragStartY,\n start: {\n width:\n (component?.props?.width as Dim)?.value ??\n (component?.props?.size as Dim)?.value ??\n 0,\n height: (component?.props?.height as Dim)?.value ?? 0,\n },\n resizedPosition: position,\n widthToUpdate: null,\n heightToUpdate: null,\n isApplyingResize: false,\n });\n }\n\n private calculateDimension(baseValue: number, delta: number): number {\n return Math.floor(Math.max(baseValue + delta, 0));\n }\n\n private handleResizeDimension(params: {\n resizeState: ResizeState;\n dimension: \"width\" | \"height\";\n delta: number;\n canResize: boolean;\n mode: string;\n position: string;\n }) {\n const { resizeState, dimension, delta, canResize, position } = params;\n if (!canResize) return;\n\n const isHorizontal = dimension === \"width\";\n const startValue = resizeState.start[dimension];\n\n let newValue = null;\n\n if (position.includes(isHorizontal ? \"left\" : \"top\")) {\n newValue = this.calculateDimension(startValue, -delta);\n } else if (position.includes(isHorizontal ? \"right\" : \"bottom\")) {\n newValue = this.calculateDimension(startValue, delta);\n }\n\n return () => {\n if (newValue) {\n resizeState[`${dimension}ToUpdate`] = Dim.px(newValue);\n }\n };\n }\n\n public resizeWidget(\n currentX: number,\n currentY: number,\n selectorId: SbSelector,\n canResizeWidth: boolean,\n canResizeHeight: boolean,\n ) {\n const sourceId =\n this.root.editStore?.runtimeTrackingStore.getSourceId(selectorId);\n const component =\n this.root.editStore?.runtimeTrackingStore.getComponent(selectorId);\n const type = component?.type;\n if (!type) {\n return;\n }\n const resizeState = sourceId && this._activeResizes.get(sourceId);\n if (!resizeState) {\n return;\n }\n const widthMode = (component?.props?.width as Dim)?.mode;\n const heightMode = (component?.props?.height as Dim)?.mode;\n const lockedAspectRatio = this.isLockedAspectRatio(selectorId);\n\n const deltaX = currentX - resizeState.dragStartX;\n const deltaY = lockedAspectRatio\n ? deltaX\n : currentY - resizeState.dragStartY;\n\n const updateWidth = this.handleResizeDimension({\n resizeState,\n dimension: \"width\",\n delta: deltaX,\n canResize: canResizeWidth,\n mode: widthMode,\n position: resizeState.resizedPosition,\n });\n\n const updateHeight = this.handleResizeDimension({\n resizeState,\n dimension: \"height\",\n delta: deltaY,\n canResize: canResizeHeight,\n mode: heightMode,\n position: resizeState.resizedPosition,\n });\n\n if (updateWidth) {\n updateWidth();\n }\n if (updateHeight) {\n updateHeight();\n }\n\n this._activeResizes.set(sourceId, resizeState);\n }\n\n // sourceId rather than instance because we are resizing all items of this source at the same time.\n public pendingResize(sourceId: SbElement) {\n const resizeState = this._activeResizes.get(sourceId);\n if (!resizeState) {\n return null;\n }\n return {\n width: resizeState.widthToUpdate,\n height: resizeState.heightToUpdate,\n };\n }\n\n public get hasAnyPendingResize() {\n return Array.from(this._activeResizes.values()).some(\n // Margins are not here because they are not part of the actual resizing, they are just to improve the UX with the positioning\n (state) => state.widthToUpdate || state.heightToUpdate,\n );\n }\n\n public get pendingResizes() {\n return Array.from(this._activeResizes.values()).filter(\n (state) => !state.isApplyingResize,\n );\n }\n\n public applyResize(selectorId: SbSelector) {\n const sourceId =\n this.root.editStore?.runtimeTrackingStore.getSourceId(selectorId);\n const component =\n this.root.editStore?.runtimeTrackingStore.getComponent(selectorId);\n const type = component?.type;\n if (!type) {\n return;\n }\n const resizeState = sourceId && this._activeResizes.get(sourceId);\n if (!resizeState) {\n return;\n }\n\n resizeState.isApplyingResize = true;\n\n const properties: Record<string, PropertyInfo<unknown>> = {\n ...(resizeState.heightToUpdate &&\n type !== \"Icon\" && {\n height: Property.Dimension(resizeState.heightToUpdate),\n }),\n ...(resizeState.widthToUpdate &&\n type !== \"Icon\" && {\n width: Property.Dimension(resizeState.widthToUpdate),\n }),\n ...(resizeState.widthToUpdate &&\n type === \"Icon\" && {\n size: Property.Dimension(resizeState.widthToUpdate),\n }),\n };\n\n if (Object.keys(properties).length > 0) {\n this.root.editStore?.operationManager.setWidgetProperties({\n sourceId: resizeState.sourceId,\n properties,\n callback: () => {\n this._activeResizes.delete(sourceId);\n },\n });\n }\n }\n}\n","import { action, makeObservable, observable, when } from \"mobx\";\nimport { editorBridge } from \"../superblocks-editor-bridge.js\";\nimport { ResizingManager } from \"./resizing-store.js\";\nimport type { RootStore } from \"../../lib/internal-details/lib/root-store.js\";\nimport type { EditStore } from \"../edit-store.js\";\nimport type {\n SbElement,\n SbSelector,\n} from \"@superblocksteam/library-shared/types\";\n\nconst MULTI_SELECT_ENABLED = false; // TODO https://linear.app/superblocks/issue/FE-1673\n\nclass UIStore {\n resizing: ResizingManager;\n\n // TODO (Alex): audit ALL usage of these 4 to ensure interactions work correctly\n private _selectedSourceIds: SbElement[] = [];\n private _selectedSelectorIds: SbSelector[] = [];\n private _focusedSelectorId: SbSelector | null = null;\n\n private _rootInstanceData: Map<\n SbSelector,\n {\n sourceId: SbElement;\n isRoot: boolean;\n }\n > = new Map();\n\n private newComponentSelectPromise:\n | (Promise<void> & { cancel(): void })\n | null = null;\n\n constructor(\n readonly root: RootStore,\n readonly editStore: EditStore,\n ) {\n this.resizing = new ResizingManager(root);\n\n makeObservable<\n UIStore,\n \"_selectedSourceIds\" | \"_selectedSelectorIds\" | \"_focusedSelectorId\"\n >(this, {\n _selectedSourceIds: observable,\n _selectedSelectorIds: observable,\n _focusedSelectorId: observable,\n\n setSelectedSourceIds: action,\n setSelectedSelectorIds: action,\n setFocusedIds: action,\n selectWidget: action,\n });\n }\n\n /*\n * This is a optimistic way to improve the UX for repeated elements.\n * The IDEAL solution would be that the editor frame knows about selector IDs too. For now, this should work in most cases.\n *\n * This works like returning getSelectorIdsForSourceId except for 1 case.\n * If there is a singularly selected component and there are multiple components that match the given source ID,\n * we should try to find the correct component by seeing if new source ID is an ancestor of the selected component.\n */\n getMostRelevantSelectorIdsForSourceId(sourceId: SbElement): SbSelector[] {\n const selectorIds =\n this.editStore.runtimeTrackingStore.getSelectorIdsForSourceId(sourceId);\n const selectedSelectorIds = this.getSelectedSelectorIds();\n if (selectorIds.size <= 1 || selectedSelectorIds.length !== 1) {\n // tiny optimization - if there's only 1 selectorId that matches the source, then we don't need anything fancy\n // another optimization, if there are MULTIPLE selected selectorIDs, then we should just skip this step in case its too costly\n return Array.from(selectorIds);\n }\n\n const getSelectorIdMatchingSourceIdInAncestry = (\n selId: SbSelector,\n srcId: SbElement,\n maxDepth = 10,\n ): null | SbSelector => {\n if (maxDepth <= 0) {\n return null;\n }\n if (this.editStore.runtimeTrackingStore.getSourceId(selId) === srcId) {\n return selId;\n }\n const parentSelectorId =\n this.editStore.runtimeTrackingStore.getComponentParent(selId);\n if (parentSelectorId) {\n return getSelectorIdMatchingSourceIdInAncestry(\n parentSelectorId,\n srcId,\n maxDepth - 1,\n );\n }\n return null;\n };\n\n const matchingSelectorId = getSelectorIdMatchingSourceIdInAncestry(\n selectedSelectorIds[0],\n sourceId,\n );\n if (matchingSelectorId) {\n return [matchingSelectorId];\n }\n\n return Array.from(selectorIds);\n }\n\n // TODO (Alex): For these getters, we should differentiate between source and instance selection\n isSourceSelected(sourceId: SbElement) {\n if (this._selectedSourceIds.includes(sourceId)) {\n return true;\n }\n const selectorIds =\n this.editStore.runtimeTrackingStore.getSelectorIdsForSourceId(sourceId);\n return (\n selectorIds != null &&\n Array.from(selectorIds).some((selectorId) =>\n this._selectedSelectorIds.includes(selectorId),\n )\n );\n }\n getSelectedSourceIds(): SbElement[] {\n const sourceSet = new Set<SbElement>();\n this._selectedSourceIds.forEach((sourceId) => {\n sourceSet.add(sourceId);\n });\n this._selectedSelectorIds.forEach((selectorId) => {\n const sourceId =\n this.editStore.runtimeTrackingStore.getSourceId(selectorId);\n if (sourceId) {\n sourceSet.add(sourceId);\n }\n });\n return Array.from(sourceSet);\n }\n\n getSelectedSelectorIds(): SbSelector[] {\n return this._selectedSelectorIds;\n }\n\n private get focusedSelectorId(): SbSelector | null {\n return this._focusedSelectorId;\n }\n\n getFocusedSourceId(): SbElement | null {\n if (!this._focusedSelectorId) {\n return null;\n }\n return (\n this.editStore.runtimeTrackingStore.getSourceId(\n this._focusedSelectorId,\n ) ?? null\n );\n }\n getFocusedSelectorId(): SbSelector | null {\n return this.focusedSelectorId;\n }\n // End of getters that need to be eventually improved\n\n setSelectedSourceIds(sourceIds: SbElement[]) {\n this.newComponentSelectPromise?.cancel();\n this.subscribeNewSourceIdsToRuntimeSync(sourceIds);\n this._selectedSourceIds = sourceIds;\n }\n\n private subscribeNewSourceIdsToRuntimeSync(sourceIds: SbElement[]) {\n const previousSourceIds = new Set(this._selectedSourceIds);\n const newSourceIds = new Set(sourceIds);\n\n previousSourceIds.forEach((sourceId) => {\n if (!newSourceIds.has(sourceId)) {\n this.editStore.runtimeSubscriptionsStore.unsubscribe(sourceId);\n }\n });\n\n newSourceIds.forEach((sourceId) => {\n if (!previousSourceIds.has(sourceId)) {\n this.editStore.runtimeSubscriptionsStore.subscribe(sourceId);\n }\n });\n }\n\n setSelectedSelectorIds(selectorIds: SbSelector[]) {\n this.newComponentSelectPromise?.cancel();\n this._selectedSelectorIds = selectorIds;\n }\n\n setFocusedIds(selectorId: SbSelector | null) {\n this._focusedSelectorId = selectorId;\n }\n\n selectWidget(\n selectorId: SbSelector | null,\n _addToSelection: boolean = false,\n ) {\n this.newComponentSelectPromise?.cancel();\n const addToSelection = _addToSelection && MULTI_SELECT_ENABLED;\n\n const component =\n selectorId &&\n this.editStore.runtimeTrackingStore.getComponent(selectorId);\n const sourceId = component?.sourceId;\n\n if (!component || !sourceId) {\n editorBridge.selectWidgets([]);\n this.setSelectedSourceIds([]);\n this.setSelectedSelectorIds([]);\n this.editStore.propertiesPanelManager.untrackPropertiesPanel();\n\n // Unlock design mode when deselecting\n if (this.editStore.interactionMode === \"design\") {\n this.editStore.setDesignModeLocked(false);\n }\n return;\n }\n\n const sourceIds = addToSelection\n ? [...this._selectedSourceIds, sourceId]\n : [sourceId];\n const selectorIds = addToSelection\n ? [...this._selectedSelectorIds, selectorId]\n : [selectorId];\n this.setSelectedSourceIds(sourceIds);\n this.setSelectedSelectorIds(selectorIds);\n\n this.editStore.propertiesPanelManager.trackPropertiesPanel(selectorId);\n\n editorBridge.selectWidgets(sourceIds, selectorId);\n\n // Lock design mode when a widget is selected in design mode\n if (this.editStore.interactionMode === \"design\") {\n this.editStore.setDesignModeLocked(true);\n }\n }\n\n /**\n * This is cursed because component selection actually needs to be done by instance ids, but\n * instance IDs are only guaranteed to be stable after the component is rendered, while source IDs\n * are assigned by the source tracker.\n *\n * If _any_ other selection comes in before we select something, we will cancel this reaction\n */\n async selectNewComponentBySourceId(\n sourceId: SbElement,\n selectorIdsToIgnore = new Set<SbSelector>(),\n ) {\n this.newComponentSelectPromise?.cancel();\n\n // first select the instance id that is already rendered, it will be an optimistic instance id\n this.newComponentSelectPromise = when(() =>\n Array.from(\n this.editStore.runtimeTrackingStore.getSelectorIdsForSourceId(sourceId),\n ).some((selectorId) => !selectorIdsToIgnore.has(selectorId)),\n );\n await this.newComponentSelectPromise;\n\n const selectorId = Array.from(\n this.editStore.runtimeTrackingStore.getSelectorIdsForSourceId(sourceId),\n )[0];\n if (selectorId) {\n this.selectWidget(selectorId);\n }\n }\n}\n\nexport default UIStore;\n","import type { EditStore } from \"../edit-store.js\";\nimport type RuntimeTrackingStore from \"../features/runtime-tracking-store.js\";\nimport type { ComponentNode } from \"../runtime-graph/types.js\";\nimport type {\n RuntimeSyncComposite,\n RuntimeSyncComponentData,\n RuntimeSyncComponentMetadata,\n RuntimeSyncSubtreeNode,\n} from \"@superblocksteam/library-shared/types\";\nimport type {\n SbElement,\n SbSelector,\n} from \"@superblocksteam/library-shared/types\";\n\ntype RuntimeComposite = RuntimeSyncComposite;\ntype RuntimeComponentData = RuntimeSyncComponentData;\ntype PathNode = RuntimeSyncComponentMetadata;\ntype SubtreeNode = RuntimeSyncSubtreeNode;\n\nexport type SubscribeParams = {\n sourceId: SbElement;\n};\n\nconst MAX_SUBTREE_DEPTH = 30;\n\nexport function buildComposite(\n editStore: EditStore,\n params: SubscribeParams,\n): RuntimeComposite | null {\n const { sourceId } = params;\n\n const runtimeStore = editStore.runtimeTrackingStore;\n\n const selectorIds =\n editStore.ui.getMostRelevantSelectorIdsForSourceId(sourceId);\n\n if (selectorIds.length === 0) {\n return null;\n }\n\n // if there are multiple, just select the first one\n const selectorId = selectorIds[0];\n\n const componentNode = runtimeStore.getComponent(selectorId);\n if (!componentNode) {\n return null;\n }\n\n const component: RuntimeComponentData = {\n selectorId: componentNode.selectorId,\n sourceId: componentNode.sourceId,\n type: getComponentType(componentNode),\n displayName: runtimeStore.getDisplayName(selectorId),\n isSbComponent: componentNode.isSbComponent,\n isHtmlElement: componentNode.isHtmlElement,\n props: componentNode.props,\n };\n\n const parentSelectorId = runtimeStore.getComponentParent(selectorId) as\n | SbSelector\n | undefined;\n const parent = parentSelectorId\n ? buildComponentData(runtimeStore, parentSelectorId)\n : null;\n\n const children = buildChildren(runtimeStore, selectorId);\n const path = buildPathToRoot(runtimeStore, selectorId);\n\n const subtreeRoot = buildSubtreeNode(\n runtimeStore,\n selectorId,\n MAX_SUBTREE_DEPTH,\n );\n\n return {\n component,\n parent,\n children,\n path,\n subtree: subtreeRoot ?? undefined,\n };\n}\n\nfunction buildComponentData(\n store: RuntimeTrackingStore,\n selectorId: SbSelector,\n): RuntimeComponentData | null {\n const componentNode = store.getComponent(selectorId);\n if (!componentNode) {\n return null;\n }\n\n return {\n selectorId: componentNode.selectorId,\n sourceId: componentNode.sourceId,\n type: getComponentType(componentNode),\n displayName: store.getDisplayName(selectorId),\n isSbComponent: componentNode.isSbComponent,\n isHtmlElement: componentNode.isHtmlElement,\n props: componentNode.props,\n };\n}\n\nfunction buildChildren(\n store: RuntimeTrackingStore,\n selectorId: SbSelector,\n): RuntimeComponentData[] {\n const childSelectorIds = store.getComponentChildren(selectorId);\n return childSelectorIds\n .map((childId) => buildComponentData(store, childId))\n .filter(Boolean) as RuntimeComponentData[];\n}\n\nfunction buildPathToRoot(\n store: RuntimeTrackingStore,\n selectorId: SbSelector,\n): PathNode[] {\n const path: PathNode[] = [];\n let current: SbSelector | undefined = selectorId;\n const visited = new Set<SbSelector>();\n\n while (current && !visited.has(current)) {\n visited.add(current);\n\n const component = store.getComponent(current);\n if (component && !component.noSelect) {\n path.unshift({\n selectorId: component.selectorId,\n sourceId: component.sourceId,\n displayName: store.getDisplayName(current),\n type: getComponentType(component),\n });\n }\n current = store.getComponentParent(current) as SbSelector | undefined;\n }\n\n if (current && visited.has(current)) {\n console.warn(\n `[RuntimeSync] Cycle detected in component graph at ${current}`,\n );\n }\n\n return path;\n}\n\nfunction buildSubtreeNode(\n store: RuntimeTrackingStore,\n selectorId: SbSelector,\n remainingDepth: number,\n): SubtreeNode | null {\n const component = store.getComponent(selectorId);\n if (!component) {\n return null;\n }\n\n const children: SubtreeNode[] = [];\n\n if (remainingDepth > 0) {\n const childSelectorIds = store.getComponentChildren(selectorId);\n for (const childId of childSelectorIds) {\n const childNode = buildSubtreeNode(store, childId, remainingDepth - 1);\n if (childNode) {\n children.push(childNode);\n }\n }\n }\n\n return {\n selectorId,\n sourceId: component.sourceId,\n displayName: store.getDisplayName(selectorId),\n type: getComponentType(component),\n children,\n };\n}\n\nfunction getComponentType(component: ComponentNode): string {\n if (typeof component.type === \"function\") {\n return component.type.name;\n }\n if (typeof component.type === \"string\") {\n return component.type;\n }\n return \"Component\";\n}\n","import { makeAutoObservable, observable, action, computed } from \"mobx\";\nimport { buildComposite } from \"./builders.js\";\nimport type { EditStore } from \"../edit-store.js\";\nimport type { RuntimeSyncComposite } from \"@superblocksteam/library-shared/types\";\nimport type { SbElement } from \"@superblocksteam/library-shared/types\";\n\n/**\n * MobX store that manages runtime component subscriptions.\n * Tracks which components are subscribed and builds fresh composites on-demand.\n * The subscriptions getter allows startEditorSync reactions to track deep observables\n * from buildComposite, eliminating the need for manual reaction management.\n */\nexport class RuntimeSubscriptionsStore {\n private subscribedSourceIds = observable.set<SbElement>();\n\n constructor(readonly editStore: EditStore) {\n makeAutoObservable(this, {\n subscribe: action,\n unsubscribe: action,\n clearAll: action,\n subscriptions: computed,\n });\n }\n\n subscribe(sourceId: SbElement): void {\n this.subscribedSourceIds.add(sourceId);\n }\n\n unsubscribe(sourceId: SbElement): void {\n this.subscribedSourceIds.delete(sourceId);\n }\n\n clearAll(): void {\n this.subscribedSourceIds.clear();\n }\n\n get subscriptions(): Record<SbElement, RuntimeSyncComposite | null> {\n const out: Record<SbElement, RuntimeSyncComposite | null> = {};\n this.subscribedSourceIds.forEach((sourceId) => {\n out[sourceId] = buildComposite(this.editStore, {\n sourceId,\n });\n });\n return out;\n }\n}\n","import { OBS_TAG_APPLICATION_ID } from \"@superblocksteam/shared\";\nimport { action, makeObservable, observable } from \"mobx\";\nimport posthog from \"posthog-js\";\nimport { isEditMode } from \"../lib/internal-details/is-edit-mode.js\";\nimport rootStore from \"../lib/internal-details/lib/root-store.js\";\nimport { AiManager } from \"./features/ai-store.js\";\nimport ConnectionManager from \"./features/connection-manager.js\";\nimport OperationManager from \"./features/operation-store.js\";\nimport PropertiesPanelManager from \"./features/properties-panel-manager.js\";\nimport RuntimeTrackingStore from \"./features/runtime-tracking-store.js\";\nimport UIStore from \"./features/ui-store.js\";\nimport { startEditorSync } from \"./mobx-sync/mobx-editor-sync.js\";\nimport { RuntimeSubscriptionsStore } from \"./runtime-sync/runtime-subscriptions-store.js\";\n\nimport { editorBridge } from \"./superblocks-editor-bridge.js\";\nimport type { RootStore } from \"../lib/internal-details/lib/root-store.js\";\nimport type {\n ViteMessageKind,\n ViteMessage,\n InteractionMode,\n} from \"@superblocksteam/library-shared/types\";\n\ndeclare global {\n interface Window {\n _SB_ENABLE_SESSION_RECORDING?: boolean;\n __SUPERBLOCKS_EDITOR_HOOK__: InstanceType<typeof EditStore>;\n }\n}\n\nconst isSessionRecordingEnabled = (): boolean => {\n return window._SB_ENABLE_SESSION_RECORDING ?? false;\n};\n\n// A single instance of this is created and attached to the root store when the app is using edit mode\nexport class EditStore {\n ui: UIStore;\n operationManager: OperationManager;\n propertiesPanelManager: PropertiesPanelManager;\n runtimeTrackingStore: RuntimeTrackingStore;\n connectionManager: ConnectionManager;\n ai: AiManager;\n runtimeSubscriptionsStore: RuntimeSubscriptionsStore;\n\n isInitialized = false;\n recordingInitialized = false;\n interactionMode: InteractionMode = \"interactive\";\n\n // for certain interactions around hotkeys\n lastInteractionMode: InteractionMode = \"interactive\";\n\n // Track if design mode should persist after Meta key release (locked after selection)\n isDesignModeLocked = false;\n\n private viteMessageListeners: Map<\n ViteMessageKind,\n Array<(message: any) => void>\n > = new Map();\n\n constructor(rootStore: RootStore) {\n this.ui = new UIStore(rootStore, this);\n this.operationManager = new OperationManager();\n this.propertiesPanelManager = new PropertiesPanelManager(\n this,\n rootStore.componentRegistry,\n );\n this.runtimeTrackingStore = new RuntimeTrackingStore(this);\n this.runtimeSubscriptionsStore = new RuntimeSubscriptionsStore(this);\n this.connectionManager = new ConnectionManager();\n this.ai = new AiManager(this.runtimeTrackingStore);\n makeObservable(this, {\n isInitialized: observable,\n interactionMode: observable,\n isDesignModeLocked: observable,\n setIsInitialized: action,\n setInteractionMode: action,\n setDesignModeLocked: action,\n });\n }\n\n setIsInitialized(isInitialized: boolean) {\n if (this.isInitialized) return;\n this.isInitialized = isInitialized;\n\n if (isInitialized) {\n startEditorSync({\n store: this.runtimeSubscriptionsStore,\n storeId: \"runtimeSync\",\n projection: (store) => store.subscriptions,\n });\n }\n }\n\n setInteractionMode(mode: InteractionMode, notifyEditor = false) {\n if (this.interactionMode === mode) {\n return;\n }\n\n this.lastInteractionMode = this.interactionMode;\n this.interactionMode = mode;\n\n // Reset design mode lock when entering design mode or exiting to other modes\n if (mode === \"design\") {\n this.isDesignModeLocked = false;\n } else if (this.lastInteractionMode === \"design\") {\n this.isDesignModeLocked = false;\n }\n\n if (notifyEditor) {\n editorBridge.setInteractionMode(mode);\n }\n }\n\n setDesignModeLocked(locked: boolean) {\n this.isDesignModeLocked = locked;\n }\n\n onViteMessage<\n T extends ViteMessageKind,\n Message extends Extract<ViteMessage, { kind: T }>,\n >(kind: T, callback: (message: Message) => void) {\n this.viteMessageListeners.set(kind, [\n ...(this.viteMessageListeners.get(kind) || []),\n callback,\n ]);\n\n return () => {\n this.viteMessageListeners.set(\n kind,\n this.viteMessageListeners.get(kind)?.filter((cb) => cb !== callback) ||\n [],\n );\n };\n }\n\n triggerViteMessage<\n T extends ViteMessageKind,\n Message extends Extract<ViteMessage, { kind: T }>,\n >(kind: T, message: Message) {\n this.viteMessageListeners.get(kind)?.forEach((cb) => cb(message));\n }\n\n startRecording(recording: {\n userId: string;\n appId: string;\n sessionRecordingKey: string;\n }) {\n if (this.recordingInitialized || !isSessionRecordingEnabled()) {\n return;\n }\n\n posthog.init(recording.sessionRecordingKey, {\n api_host: \"https://us.i.posthog.com\",\n defaults: \"2025-05-24\",\n session_recording: {\n recordCrossOriginIframes: true,\n },\n });\n posthog.identify(recording.userId);\n posthog.register({\n [OBS_TAG_APPLICATION_ID]: recording.appId,\n });\n this.recordingInitialized = true;\n }\n}\n\nif (!window.__SUPERBLOCKS_EDITOR_HOOK__ && isEditMode()) {\n // Singleton instance for global access to EditStore\n const editStore = new EditStore(rootStore);\n window.__SUPERBLOCKS_EDITOR_HOOK__ = editStore;\n rootStore.setEditStore(editStore);\n}\n\nexport function initializeEditStore() {\n if (!window.__SUPERBLOCKS_EDITOR_HOOK__) {\n return;\n }\n window.__SUPERBLOCKS_EDITOR_HOOK__.setIsInitialized(true);\n}\n","import { useHotkeys as useHotkeysOriginal } from \"react-hotkeys-hook\";\nimport type { KeyHandler } from \"hotkeys-js\";\nimport type { Options } from \"react-hotkeys-hook\";\n\nexport function useEditorHotkeys<T extends Element>(\n keys: string,\n callback: KeyHandler,\n options?: any[] | Options,\n deps?: any[],\n): React.MutableRefObject<T | null> | undefined {\n if (options instanceof Array) {\n deps = options;\n options = undefined;\n }\n\n return useHotkeysOriginal(keys, callback, options, [...(deps ?? []), false]);\n}\n","import { useEffect, useRef } from \"react\";\n\nexport function useKeyPressed(\n key: string,\n callback: (isPressed: boolean) => void,\n options?: {\n /** Delay in milliseconds before triggering the pressed callback. Default: 0 (immediate) */\n pressDelay?: number;\n /** Whether to allow multiple keys to be pressed at the same time. Default: true */\n allowMultipleKeys?: boolean;\n },\n) {\n const timeoutRef = useRef<NodeJS.Timeout | null>(null);\n const isKeyDownRef = useRef<boolean>(false);\n\n useEffect(() => {\n const handleKeyDown = (e: KeyboardEvent) => {\n if (e.key === key && !e.repeat) {\n if (\n ((e.ctrlKey && key.toLowerCase() !== \"ctrl\") ||\n (e.metaKey && key.toLowerCase() !== \"meta\") ||\n (e.altKey && key.toLowerCase() !== \"alt\") ||\n (e.shiftKey && key.toLowerCase() !== \"shift\")) &&\n !options?.allowMultipleKeys\n ) {\n if (timeoutRef.current) {\n clearTimeout(timeoutRef.current);\n timeoutRef.current = null;\n }\n isKeyDownRef.current = false;\n callback(false);\n return;\n }\n\n isKeyDownRef.current = true;\n\n if (options?.pressDelay && options.pressDelay > 0) {\n // Clear any existing timeout\n if (timeoutRef.current) {\n clearTimeout(timeoutRef.current);\n }\n\n // Set timeout for delayed execution\n timeoutRef.current = setTimeout(() => {\n callback(true);\n }, options.pressDelay);\n } else {\n // Immediate execution (default behavior)\n callback(true);\n }\n } else if (\n e.key !== key &&\n isKeyDownRef.current &&\n options?.allowMultipleKeys === false\n ) {\n // Another key was pressed while the target key is down\n if (timeoutRef.current) {\n clearTimeout(timeoutRef.current);\n timeoutRef.current = null;\n }\n callback(false);\n isKeyDownRef.current = false;\n }\n };\n\n const handleKeyUp = (e: KeyboardEvent) => {\n if (e.key === key) {\n // Clear timeout if key is released before delay\n if (timeoutRef.current) {\n clearTimeout(timeoutRef.current);\n timeoutRef.current = null;\n }\n\n isKeyDownRef.current = false;\n\n // Always execute release logic immediately\n callback(false);\n }\n };\n\n const handleVisibilityChange = () => {\n if (document.hidden) {\n isKeyDownRef.current = false;\n callback(false);\n }\n };\n\n const handleBlur = () => {\n isKeyDownRef.current = false;\n callback(false);\n };\n\n document.addEventListener(\"keydown\", handleKeyDown);\n document.addEventListener(\"keyup\", handleKeyUp);\n document.addEventListener(\"visibilitychange\", handleVisibilityChange);\n document.addEventListener(\"blur\", handleBlur);\n\n return () => {\n document.removeEventListener(\"keydown\", handleKeyDown);\n document.removeEventListener(\"keyup\", handleKeyUp);\n document.removeEventListener(\"visibilitychange\", handleVisibilityChange);\n document.removeEventListener(\"blur\", handleBlur);\n if (timeoutRef.current) {\n clearTimeout(timeoutRef.current);\n }\n };\n }, [key, callback, options?.pressDelay, options?.allowMultipleKeys]);\n}\n","import { computed, reaction } from \"mobx\";\nimport { useEffect, useMemo, useState, useRef } from \"react\";\nimport type { IComputedValue } from \"mobx\";\n\n/**\n * The component that uses this hook must be wrapped `observer`, otherwise state changes will not\n * cause this hook to re-run.\n */\nexport const useObserverMemo = <T>(fn: () => T, deps: any[]) => {\n return useMemo<IComputedValue<T>>(() => {\n return computed(fn);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, deps).get();\n};\n\n/**\n * Like useObserverMemo, but does not require the component to be wrapped in an observer.\n * It is recommended to use useObserverMemo instead.\n * @see useObserverMemo\n *\n * Note: This implementation uses MobX reactions to track both observable changes and\n * dependency changes.\n */\nexport const useStandaloneObserverMemo = <T>(fn: () => T, deps: any[]) => {\n const fnRef = useRef(fn);\n fnRef.current = fn;\n\n const [result, setResult] = useState<T>(fnRef.current);\n useEffect(\n () =>\n reaction(() => fnRef.current(), setResult, {\n fireImmediately: true,\n name: \"useStandaloneObserverMemo\",\n }),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n deps,\n );\n\n return result;\n};\n","enum Indices {\n Layer0 = 60,\n Layer1,\n Layer2,\n Layer3,\n Layer4,\n Layer5,\n Layer6,\n Layer7,\n Layer8,\n Layer9,\n Layer10,\n Layer11,\n Layer12,\n Layer13,\n Layer14,\n LayerMax = 99999,\n}\n\n// the inside canvas layers and outside layers will not interfere with each other\n// TODO: split them into two Layer objects\nexport const Layers = {\n //-------------- inside canvas --------------\n\n dragPreview: Indices.Layer1,\n\n visibilityOverlay: Indices.Layer4,\n selectedRect: Indices.Layer4, // interaction rect\n focusedRect: Indices.Layer5,\n namePill: Indices.Layer6, // interaction rect name pill\n\n closeButton: Indices.Layer4, // modal or slideout close button\n stickySections: Indices.Layer3,\n scrollbars: Indices.Layer5, // for ScrollContainer, inside positionedWidget\n componentBorder: Indices.Layer3, // for containers\n resizeWrapper: Indices.Layer4, // inside positioned widget, always show\n // only show when focused/selected, in parallel with widgetName\n // selectedWrapper: Indices.Layer4,\n\n parentSelectedWrapper: Indices.Layer3,\n widgetResizer: Indices.Layer4, // widget resizer which is 4 edges and 4 corners\n // TODO: refactor the resizer below, looks like some is not needed.\n resizer: Indices.Layer6, // section column resizer and resizer disabled tooltip,\n dialog: Indices.Layer7, // for dialog component or detached components (such as slideouts, modals)\n\n widgetName: Indices.Layer4,\n selectionConstraintResize: Indices.Layer4, // min max height constraint\n canvasBreadCrumbPopover: Indices.Layer5,\n // layers for vstack dnd\n vstackDropPlaceholder: Indices.Layer2,\n focusedInput: Indices.Layer14, // blueprint control group focused input\n\n max: Indices.LayerMax,\n};\n","import {\n SELECTOR_ID_ATTRIBUTE,\n SOURCE_ID_ATTRIBUTE,\n} from \"@superblocksteam/library-shared\";\nimport type {\n SbElement,\n SbSelector,\n} from \"@superblocksteam/library-shared/types\";\n\nexport const getBoundingBoxForWidget = (selectorId: SbSelector) => {\n return getWidgetNode(selectorId)?.getBoundingClientRect();\n};\n\n/**\n * Get the DOM node for a widget by either selector ID or source ID.\n *\n * In the frameworkless component world, raw components may not have instance IDs\n * in the DOM, but they always have source IDs. This function handles both cases.\n *\n * @param idOrSourceId - Either a selector ID (starts with \"S-\") or source ID (starts with \"SB-\")\n * @returns The DOM element or null if not found\n */\nexport const getWidgetNode = (\n idOrSourceId: SbSelector | SbElement,\n): HTMLElement | null => {\n const isSelectorId = idOrSourceId.startsWith(\"S-\");\n const isSourceId = idOrSourceId.startsWith(\"SB-\");\n if (isSelectorId) {\n const element = document?.querySelector(\n `[${SELECTOR_ID_ATTRIBUTE}=\"${idOrSourceId}\"]`,\n ) as HTMLElement | null;\n return element;\n } else if (isSourceId) {\n // Fallback to source ID lookup (works for raw frameworkless components)\n return document?.querySelector(\n `[${SOURCE_ID_ATTRIBUTE}=\"${idOrSourceId}\"]`,\n ) as HTMLElement | null;\n }\n\n throw new Error(`Unknown ID format: ${idOrSourceId} (expected S-* or SB-*)`);\n};\n\nexport const getComputedStyle = (\n selectorId: SbSelector,\n): CSSStyleDeclaration | null => {\n if (typeof window === \"undefined\") {\n return null;\n }\n\n try {\n const element = document.querySelector(\n `[${SELECTOR_ID_ATTRIBUTE}=\"${selectorId}\"]`,\n ) as HTMLElement | null;\n if (!element) {\n return null;\n }\n return window.getComputedStyle(element);\n } catch {\n return null;\n }\n};\n\nexport const getFlexDirection = (\n computedStyles: CSSStyleDeclaration | null,\n): \"row\" | \"column\" | undefined => {\n if (!computedStyles) {\n return undefined;\n }\n\n try {\n const display = computedStyles.display;\n\n if (display !== \"flex\" && display !== \"inline-flex\") {\n // TODO: Handle other display types\n return undefined;\n }\n\n const flexDirection = computedStyles.flexDirection;\n if (flexDirection === \"column\" || flexDirection === \"column-reverse\") {\n return \"column\";\n } else if (flexDirection === \"row\" || flexDirection === \"row-reverse\") {\n return \"row\";\n }\n\n return \"row\"; // Default flex direction\n } catch {\n return undefined;\n }\n};\n","import { observer } from \"mobx-react-lite\";\nimport { getEditStore } from \"../get-edit-store.js\";\nimport { editorBridge } from \"../superblocks-editor-bridge.js\";\nimport type { SbSelector } from \"@superblocksteam/library-shared/types\";\n\nconst NamePillDiv = (params: {\n displayName: string;\n selectorId: SbSelector;\n type: \"SELECTED\" | \"FOCUSED\" | \"TARGETED\";\n}) => {\n const { displayName, type, selectorId } = params;\n\n const sourceId = getEditStore().runtimeTrackingStore.getSourceId(selectorId);\n\n const shouldToggleComponentInAiContext =\n getEditStore().ai.shouldToggleComponentInAiContext();\n\n return (\n <div\n className=\"sb-edit-selection-name-pill\"\n data-test=\"interaction-rect-name-pill\"\n data-pill-name={displayName}\n data-pill-type={type}\n onPointerDown={(e) => {\n e.stopPropagation();\n }}\n onClick={(ev) => {\n ev.stopPropagation();\n ev.preventDefault();\n\n if (shouldToggleComponentInAiContext) {\n if (sourceId) {\n editorBridge.toggleComponentInAiContext(\n sourceId,\n selectorId,\n displayName,\n );\n }\n } else {\n getEditStore().ui.selectWidget(selectorId, ev.shiftKey === true);\n }\n }}\n >\n {displayName}\n </div>\n );\n};\n\ninterface NamePillProps {\n selectorId: SbSelector;\n displayName: string;\n type: \"SELECTED\" | \"FOCUSED\" | \"TARGETED\";\n}\n\nconst NamePill: ReturnType<typeof observer<NamePillProps>> = observer(\n (props: NamePillProps) => {\n const { selectorId, displayName, type } = props;\n\n return (\n <NamePillDiv\n displayName={displayName}\n selectorId={selectorId}\n type={type}\n />\n );\n },\n);\n\nexport default NamePill;\n","import {\n AiContextMode,\n type SbSelector,\n} from \"@superblocksteam/library-shared/types\";\nimport { useObserverMemo } from \"../../lib/hooks/use-observer-memo.js\";\nimport { Layers } from \"../../lib/user-facing/layers.js\";\nimport { getWidgetRectAnchorName } from \"../../lib/utils/widget-wrapper-naming.js\";\nimport { getEditStore } from \"../get-edit-store.js\";\nimport { getWidgetNode } from \"../interaction-utils.js\";\nimport NamePill from \"./interaction-rect-name-pill.js\";\n\n// This might be overkill but it feels OK to use.\n// Ranges from 0 to 1, where 0 is no overlap and 1 is full overlap\nconst guessOverlapAmountForNamePills = (\n selector1: SbSelector,\n selector2: SbSelector,\n) => {\n const renderedTag1 =\n getEditStore().runtimeTrackingStore.getFirstAnchorableTag(selector1);\n const renderedTag2 =\n getEditStore().runtimeTrackingStore.getFirstAnchorableTag(selector2);\n const rect1 = renderedTag1\n ? getWidgetNode(renderedTag1)?.getBoundingClientRect()\n : null;\n const rect2 = renderedTag2\n ? getWidgetNode(renderedTag2)?.getBoundingClientRect()\n : null;\n if (!rect1 || !rect2) {\n return 0;\n }\n // name pills are about 22px tall, and 70px+ wide depending on text length\n if (Math.abs(rect1.top - rect2.top) > 36) {\n return 0;\n }\n const xDelta = Math.abs(rect1.right - rect2.right);\n if (xDelta > 200) {\n return 0;\n }\n return 1 - xDelta / 200;\n};\nconst useOverlapWithOtherPillInfo = (selectorId: SbSelector) => {\n const focusedSelectorId = getEditStore().ui.getFocusedSelectorId();\n const selectorIsFocused = focusedSelectorId === selectorId;\n const somethingElseIsFocused =\n focusedSelectorId != null && !selectorIsFocused;\n const opacityValue = somethingElseIsFocused\n ? Math.min(\n 0.6,\n 1 - guessOverlapAmountForNamePills(focusedSelectorId, selectorId),\n )\n : 1;\n return opacityValue;\n};\n\nexport function InteractionRectActions(props: {\n selectorId: SbSelector;\n displayName: string;\n type: \"SELECTED\" | \"FOCUSED\" | \"TARGETED\";\n transform?: string;\n}) {\n const { selectorId, displayName, type, transform } = props;\n\n const isPrimarySelectorId = useObserverMemo(() => {\n const focusedSelectorId = getEditStore().ui.getFocusedSelectorId();\n const selectedSelectorIds = getEditStore().ui.getSelectedSelectorIds();\n\n if (type === \"SELECTED\") {\n return selectedSelectorIds.includes(selectorId);\n } else if (type === \"FOCUSED\") {\n return focusedSelectorId === selectorId;\n } else {\n return getEditStore().ai.isTargetedSelector(selectorId);\n }\n }, [type, selectorId]);\n\n const opacityValue = useOverlapWithOtherPillInfo(selectorId);\n\n if (!isPrimarySelectorId) {\n return null;\n }\n\n const aiContextMode = getEditStore().ai.getAiContextMode();\n const isAiTaggingEnabled = getEditStore().ai.getIsTaggingEnabled();\n\n const shouldHideActions = !isPrimarySelectorId;\n\n const shouldShowAiPurplePill =\n isAiTaggingEnabled &&\n (aiContextMode === AiContextMode.AUTO_SELECT ||\n (aiContextMode === AiContextMode.HIGHLIGHT && type === \"TARGETED\"));\n\n const renderedTagSelectorId =\n getEditStore().runtimeTrackingStore.getFirstAnchorableTag(selectorId);\n\n return (\n <div\n className={`sb-edit-interaction-rect-actions ${shouldShowAiPurplePill ? \"sb-edit-actions-target-mode\" : \"\"}`}\n data-sb-actions-selector-id={selectorId}\n data-sb-actions-source-id={getEditStore().runtimeTrackingStore.getSourceId(\n selectorId,\n )}\n data-test=\"sb-name-pill-container\"\n style={\n {\n ...(shouldHideActions ? { display: \"none !important\" } : {}),\n position: \"fixed\",\n bottom: \"anchor(top)\",\n right: \"anchor(right)\",\n positionAnchor: getWidgetRectAnchorName(\n renderedTagSelectorId ?? selectorId,\n ),\n visibility: \"visible\",\n marginTop: \"1px\",\n paddingBottom: \"1px\",\n zIndex: Layers.namePill,\n pointerEvents: \"all\",\n display: \"flex\",\n gap: \"2px\",\n opacity: opacityValue,\n transform,\n } as React.CSSProperties\n }\n >\n <NamePill selectorId={selectorId} displayName={displayName} type={type} />\n </div>\n );\n}\n","import { SELECTOR_ID_ATTRIBUTE } from \"@superblocksteam/library-shared\";\nimport { useEffect, useState } from \"react\";\nimport type { SbSelector } from \"@superblocksteam/library-shared/types\";\n\ninterface TransformData {\n transform: string;\n transformedElementRect?: DOMRect; // Store for percentage calculations\n}\n\nconst transformCache = new Map<SbSelector, TransformData>();\n\n/*\ncss anchor positioning doesn't take into account translate/transform as these are considered post-layout effects\ntranslations/transforms affect their children, so for a given element, we traverse upwards from that element collecting transforms\nthen we convert all from percentage to px if needed, and return them to be applied on interaction-rects \nthis is cached for performance reasons\n*/\nexport function useAnchorTransform(selectorId: SbSelector | undefined) {\n const [transformData, setTransformData] = useState<TransformData>(() => {\n if (!selectorId) return { transform: \"none\" };\n return transformCache.get(selectorId) ?? { transform: \"none\" };\n });\n\n useEffect(() => {\n const calculateTransform = () => {\n if (!selectorId) {\n setTransformData({ transform: \"none\" });\n return;\n }\n\n // Clear cache on window resize to force recalculation\n if (transformCache.has(selectorId)) {\n transformCache.delete(selectorId);\n }\n\n const element = document.querySelector(\n `[${SELECTOR_ID_ATTRIBUTE}=\"${selectorId}\"]`,\n ) as HTMLElement | null;\n if (!element) return;\n\n // Collect ALL transforms from the element and ancestors\n const transforms: Array<{ computed: string; element: HTMLElement }> = [];\n let current: HTMLElement | null = element;\n\n while (current && current !== document.body) {\n const computedStyle = getComputedStyle(current);\n\n // Check both transform and translate properties\n const transform = computedStyle.transform;\n const translate = computedStyle.translate;\n\n if (transform && transform !== \"none\") {\n transforms.push({ computed: transform, element: current });\n }\n if (translate && translate !== \"none\") {\n // Convert translate to transform for consistency\n transforms.push({\n computed: `translate(${translate})`,\n element: current,\n });\n }\n\n current = current.parentElement;\n }\n\n if (transforms.length === 0) {\n const data: TransformData = { transform: \"none\" };\n transformCache.set(selectorId, data);\n setTransformData(data);\n return;\n }\n\n // For percentage-based transforms, we need the element's dimensions\n // Use the FIRST transformed ancestor (closest to anchor element)\n const firstTransformedElement = transforms[0].element;\n const rect = firstTransformedElement.getBoundingClientRect();\n\n // Combine transforms by applying the computed transform matrix\n // The browser already handles the composition for us via getComputedStyle\n const finalTransform = transforms[0].computed;\n\n // Convert percentage-based translates to pixels\n const processedTransform = convertPercentageInTransform(\n finalTransform,\n rect.width,\n rect.height,\n );\n\n const data: TransformData = {\n transform: processedTransform,\n transformedElementRect: rect,\n };\n\n transformCache.set(selectorId, data);\n setTransformData(data);\n };\n\n // Calculate transform initially\n calculateTransform();\n\n // Add window resize listener to recalculate on window size changes\n const handleResize = () => {\n calculateTransform();\n };\n\n window.addEventListener(\"resize\", handleResize);\n window.addEventListener(\"scroll\", handleResize);\n\n // Cleanup\n return () => {\n window.removeEventListener(\"resize\", handleResize);\n window.removeEventListener(\"scroll\", handleResize);\n };\n }, [selectorId]);\n\n return transformData.transform;\n}\n\nexport function convertPercentageInTransform(\n transformValue: string,\n width: number,\n height: number,\n): string {\n // Handle matrix/matrix3d - extract translate components\n if (transformValue.startsWith(\"matrix\")) {\n return transformValue; // Already in absolute values\n }\n\n // Handle translate() or translate3d()\n const translateMatch = transformValue.match(/translate3?d?\\(([^)]+)\\)/);\n if (!translateMatch) return transformValue;\n const valueString = translateMatch[1].trim();\n const values = valueString.includes(\",\")\n ? valueString.split(\",\").map((v) => v.trim())\n : valueString.split(/\\s+/).filter((v) => v);\n\n const convertValue = (value: string, dimension: number): string => {\n if (value.includes(\"%\")) {\n const percentage = parseFloat(value);\n return `${Math.round((percentage / 100) * dimension)}px`;\n }\n return value;\n };\n\n const x = convertValue(values[0] || \"0\", width);\n const y = values[1] ? convertValue(values[1], height) : \"0px\";\n const z = values[2] || \"0px\";\n\n // Reconstruct the transform with the px values\n if (values.length > 2) {\n return transformValue.replace(\n translateMatch[0],\n `translate3d(${x}, ${y}, ${z})`,\n );\n }\n return transformValue.replace(translateMatch[0], `translate(${x}, ${y})`);\n}\n\nexport function clearTransformCache(selectorId?: SbSelector) {\n if (selectorId) {\n transformCache.delete(selectorId);\n } else {\n transformCache.clear();\n }\n}\n","import {\n AiContextMode,\n type SbElement,\n type SbSelector,\n} from \"@superblocksteam/library-shared/types\";\nimport React, { useMemo } from \"react\";\nimport { useObserverMemo } from \"../../lib/hooks/use-observer-memo.js\";\nimport { Layers } from \"../../lib/user-facing/layers.js\";\nimport {\n getWidgetAnchorName,\n getWidgetRectAnchorName,\n} from \"../../lib/utils/widget-wrapper-naming.js\";\n\nimport { getEditStore } from \"../get-edit-store.js\";\nimport { InteractionRectActions } from \"./interaction-rect-actions.jsx\";\nimport { useAnchorTransform } from \"./transform-utils.js\";\nimport type { InteractionMode } from \"@superblocksteam/library-shared/types\";\nimport type { CSSProperties } from \"react\";\n\nexport type SelectionInfo = {\n sourceId: SbElement;\n selectorId: SbSelector;\n displayName: string;\n selectionType: \"SELECTED\" | \"FOCUSED\" | \"TARGETED\";\n type: string | undefined;\n};\n\n// TODO (alex): show different rects for sourceId and instanceId - for now just using instanceId\nexport const useSelectionElements = (params: {\n focusedSourceId: SbElement | null;\n focusedSelectorId: SbSelector | null;\n selectedSourceIds: SbElement[];\n selectedSelectorIds: SbSelector[];\n targetedSourceIds: SbElement[];\n aiContextMode: AiContextMode;\n interactionMode: InteractionMode;\n}): SelectionInfo[] => {\n const {\n focusedSelectorId,\n selectedSourceIds,\n selectedSelectorIds,\n targetedSourceIds,\n aiContextMode,\n interactionMode,\n } = params;\n\n const allTargetedComponents = useMemo(() => {\n const components: { selectorId: SbSelector; sourceId: SbElement }[] = [];\n targetedSourceIds.forEach((sourceId) => {\n const selectorIds =\n getEditStore().runtimeTrackingStore.getSelectorIdsForSourceId(sourceId);\n components.push(\n ...Array.from(selectorIds).map((selectorId) => ({\n selectorId,\n sourceId,\n })),\n );\n });\n return components;\n }, [targetedSourceIds]);\n\n // TODO - restore viewport intersection\n const visibleTargetedComponents = allTargetedComponents;\n\n const selectionRects = useObserverMemo<SelectionInfo[]>(() => {\n const selectedRects: SelectionInfo[] = [];\n\n visibleTargetedComponents.forEach((component) => {\n const { type, displayName } = selectDisplayNameAndVisibility(\n component.selectorId,\n );\n\n selectedRects.push({\n sourceId: component.sourceId,\n selectorId: component.selectorId,\n displayName,\n selectionType: \"TARGETED\",\n type,\n } satisfies SelectionInfo);\n });\n\n selectedSourceIds.forEach((sourceId) => {\n const selectorIds =\n interactionMode === \"design\"\n ? getEditStore().runtimeTrackingStore.getSelectorIdsForSourceId(\n sourceId,\n )\n : selectedSelectorIds;\n\n selectorIds.forEach((selectorId) => {\n const component =\n getEditStore().runtimeTrackingStore.getComponent(selectorId);\n if (component && !targetedSourceIds.includes(component.sourceId)) {\n const displayName =\n getEditStore().runtimeTrackingStore.getDisplayName(selectorId);\n selectedRects.push({\n sourceId,\n selectorId: selectorId,\n displayName: displayName,\n selectionType: \"SELECTED\",\n type: displayName,\n } satisfies SelectionInfo);\n }\n });\n });\n\n if (\n focusedSelectorId &&\n (aiContextMode === AiContextMode.AUTO_SELECT ||\n (!selectedSelectorIds.includes(focusedSelectorId) &&\n interactionMode === \"design\"))\n ) {\n const { type, displayName, sourceId } =\n selectDisplayNameAndVisibility(focusedSelectorId);\n\n if (sourceId) {\n selectedRects.push({\n selectorId: focusedSelectorId,\n sourceId: sourceId ?? (focusedSelectorId as SbElement),\n displayName,\n selectionType: \"FOCUSED\",\n type,\n } satisfies SelectionInfo);\n }\n }\n return selectedRects;\n }, [\n visibleTargetedComponents,\n selectedSourceIds,\n selectedSelectorIds,\n focusedSelectorId,\n aiContextMode,\n targetedSourceIds,\n interactionMode,\n ]);\n\n return selectionRects;\n};\n\nexport const InteractionRectTargetBorder = ({\n selectorId,\n}: {\n selectorId: SbSelector;\n}) => {\n const renderedTagSelectorId =\n getEditStore().runtimeTrackingStore.getFirstAnchorableTag(selectorId);\n return (\n <div\n className=\"sb-target-mode-border\"\n style={\n {\n positionAnchor: getWidgetAnchorName(\n renderedTagSelectorId ?? selectorId,\n ),\n zIndex: Layers.focusedRect,\n } as CSSProperties\n }\n >\n <div className=\"sb-target-mode-border-top-right\" />\n <div className=\"sb-target-mode-border-top-left\" />\n <div className=\"sb-target-mode-border-bottom-right\" />\n <div className=\"sb-target-mode-border-bottom-left\" />\n </div>\n );\n};\n\nexport const InteractionRect = (props: {\n displayName: string;\n sourceId: SbElement;\n selectorId: SbSelector;\n selectionType: \"SELECTED\" | \"FOCUSED\" | \"TARGETED\";\n hideRectBorder?: boolean;\n type?: string;\n}) => {\n const { selectionType, selectorId } = props;\n\n const parentSelectorId =\n getEditStore().runtimeTrackingStore.getNearestSelectableAncestor(\n selectorId,\n );\n const renderedParentTagSelectorId = parentSelectorId\n ? getEditStore().runtimeTrackingStore.getFirstAnchorableTag(\n parentSelectorId,\n )\n : undefined;\n\n const renderedTagSelectorId =\n getEditStore().runtimeTrackingStore.getFirstAnchorableTag(selectorId);\n\n const aiContextMode = getEditStore().ai.getAiContextMode();\n const isAiTargeted =\n aiContextMode === AiContextMode.AUTO_SELECT ||\n aiContextMode === AiContextMode.HIGHLIGHT;\n\n const selectionClass =\n selectionType === \"FOCUSED\"\n ? \"sb-edit-focus\"\n : selectionType === \"TARGETED\"\n ? \"sb-edit-target\"\n : \"\";\n\n // get any transforms on the anchor element and apply them to the rect\n const transform = useAnchorTransform(renderedTagSelectorId ?? selectorId);\n const parentTransform = useAnchorTransform(\n renderedParentTagSelectorId ?? parentSelectorId,\n );\n\n // TODO: remove this comment\n return (\n <>\n {parentSelectorId && selectionType === \"SELECTED\" && (\n <>\n <div\n className=\"sb-edit-selection-rect\"\n data-sb-selection-type={selectionType}\n style={\n {\n position: \"fixed\",\n top: \"anchor(top)\",\n left: \"anchor(left)\",\n right: \"anchor(right)\",\n bottom: \"anchor(bottom)\",\n anchorName: getWidgetRectAnchorName(\n renderedParentTagSelectorId ?? parentSelectorId,\n ),\n positionAnchor: getWidgetAnchorName(\n renderedParentTagSelectorId ?? parentSelectorId,\n ),\n border: \"1px dashed var(--primary-rect-color)\",\n ...(props.hideRectBorder ? { border: \"none\" } : {}),\n zIndex: Layers.selectedRect,\n transform: parentTransform,\n } as any\n }\n />\n </>\n )}\n <div\n className={`sb-edit-selection-rect ${selectionClass} ${aiContextMode === AiContextMode.AUTO_SELECT ? \"sb-edit-target-mode\" : \"\"}`}\n style={\n {\n position: \"fixed\",\n top: \"anchor(top)\",\n left: \"anchor(left)\",\n right: \"anchor(right)\",\n bottom: \"anchor(bottom)\",\n anchorName: getWidgetRectAnchorName(\n renderedTagSelectorId ?? selectorId,\n ),\n positionAnchor: getWidgetAnchorName(\n renderedTagSelectorId ?? selectorId,\n ),\n ...(props.hideRectBorder ? { border: \"none\" } : {}),\n zIndex:\n selectionType === \"FOCUSED\"\n ? Layers.focusedRect\n : Layers.selectedRect,\n transform,\n } as any\n }\n />\n {/* TODO(frameworkless): restore resizing handles\n <InteractionRectHandles\n selectorId={selectorId}\n selectionType={selectionType}\n /> */}\n {isAiTargeted ? (\n selectionType === \"TARGETED\" ? (\n <InteractionRectTargetBorder selectorId={selectorId} />\n ) : null\n ) : null}\n <InteractionRectActions\n selectorId={selectorId}\n displayName={props.displayName}\n type={selectionType}\n transform={transform}\n />\n </>\n );\n};\n\nexport const selectDisplayNameAndVisibility = (\n selectorId: SbSelector,\n): {\n type: string | undefined;\n displayName: string;\n sourceId?: SbElement;\n} => {\n const component =\n getEditStore().runtimeTrackingStore.getComponent(selectorId);\n const sourceId = component?.sourceId;\n const type = component?.type;\n\n const displayName =\n getEditStore().runtimeTrackingStore.getDisplayName(selectorId) ||\n (typeof type === \"string\" ? type : type?.displayName || type?.name) ||\n \"Unknown\";\n\n return {\n type: typeof type === \"string\" ? type : type?.displayName || type?.name,\n displayName,\n sourceId,\n };\n};\n","import { AiContextMode } from \"@superblocksteam/library-shared/types\";\nimport { useEditorHotkeys } from \"../lib/hooks/use-editor-hotkeys.js\";\nimport { useKeyPressed } from \"../lib/hooks/use-key-pressed.js\";\nimport { getEditStore } from \"./get-edit-store.js\";\nimport { selectDisplayNameAndVisibility } from \"./interaction-layer/interaction-rect.js\";\nimport { editorBridge } from \"./superblocks-editor-bridge.js\";\n\nexport function EditorHotkeys({ children }: { children: React.ReactNode }) {\n useEditorHotkeys(\n \"ctrl+z, command+z\",\n (e: any) => {\n e.preventDefault();\n e.stopPropagation();\n editorBridge.undo();\n },\n {\n filterPreventDefault: false,\n },\n [],\n );\n useEditorHotkeys(\n \"c\",\n (e: any) => {\n e.preventDefault();\n e.stopPropagation();\n const selectedSourceIds = getEditStore().ui.getSelectedSourceIds();\n const selectedSelectorIds = getEditStore().ui.getSelectedSelectorIds();\n if (selectedSourceIds.length > 0) {\n editorBridge.toggleComponentInAiContext(\n selectedSourceIds[0],\n selectedSelectorIds[0],\n selectDisplayNameAndVisibility(selectedSelectorIds[0])?.displayName,\n );\n }\n },\n {\n filterPreventDefault: false,\n },\n [],\n );\n\n useEditorHotkeys(\n \"ctrl+shift+z, command+shift+z\",\n (e: any) => {\n e.preventDefault();\n e.stopPropagation();\n editorBridge.redo();\n },\n {\n filterPreventDefault: false,\n },\n [],\n );\n\n useEditorHotkeys(\"backspace, delete\", (e: any) => {\n e.preventDefault();\n e.stopPropagation();\n\n if (\n e.target instanceof HTMLInputElement ||\n e.target instanceof HTMLTextAreaElement\n ) {\n return;\n }\n const editStore = getEditStore();\n editStore.operationManager.deleteComponents(\n editStore.ui.getSelectedSourceIds(),\n );\n editStore.ui.selectWidget(null);\n });\n\n useKeyPressed(\n \"Meta\",\n (isPressed) => {\n if (isPressed) {\n editorBridge.setAiContextMode(AiContextMode.AUTO_SELECT);\n } else {\n editorBridge.setAiContextMode(AiContextMode.SILENT);\n }\n },\n { pressDelay: 100, allowMultipleKeys: false },\n );\n\n useEditorHotkeys(\n \"Meta+i, command+i\",\n (e) => {\n e.preventDefault();\n e.stopPropagation();\n const editStore = getEditStore();\n editStore.ui.selectWidget(null);\n editStore.ui.setFocusedIds(null);\n editStore.setInteractionMode(\"interactive\", true);\n },\n { enableOnTags: [\"TEXTAREA\", \"INPUT\"], enableOnContentEditable: true },\n );\n\n useEditorHotkeys(\n \"Meta+d, command+d\",\n (e) => {\n e.preventDefault();\n e.stopPropagation();\n const editStore = getEditStore();\n editorBridge.setAiContextMode(AiContextMode.SILENT);\n editStore.setInteractionMode(\"design\", true);\n },\n {\n enableOnTags: [\"TEXTAREA\", \"INPUT\"],\n enableOnContentEditable: true,\n },\n );\n\n useEditorHotkeys(\n \"esc\",\n (e: any) => {\n e.preventDefault();\n e.stopPropagation();\n const editStore = getEditStore();\n editStore.ui.selectWidget(null);\n editStore.setInteractionMode(\"interactive\", true);\n editorBridge.setAiContextMode(AiContextMode.SILENT);\n },\n {\n enableOnTags: [\"TEXTAREA\", \"INPUT\"],\n enableOnContentEditable: true,\n },\n );\n\n useEditorHotkeys(\n \"ctrl+s, command+s\",\n (e: any) => {\n e.preventDefault();\n e.stopPropagation();\n const editStore = getEditStore();\n editStore.ui.selectWidget(null);\n editorBridge.setAiContextMode(AiContextMode.SILENT);\n const lastInteractionMode = editStore.lastInteractionMode;\n if (\n editStore.interactionMode === \"interactive\" ||\n editStore.interactionMode === \"design\"\n ) {\n editStore.setInteractionMode(\"full-preview\", true);\n } else {\n editStore.setInteractionMode(lastInteractionMode, true);\n }\n },\n {\n enableOnTags: [\"TEXTAREA\", \"INPUT\", \"SELECT\"],\n enableOnContentEditable: true,\n },\n );\n\n return <>{children}</>;\n}\n","import { isEditMode } from \"../lib/internal-details/is-edit-mode.js\";\nimport { apiActivityTracker } from \"../lib/internal-details/lib/features/api-activity-tracker.js\";\nimport { iframeMessageHandler } from \"../lib/internal-details/lib/iframe.js\";\nimport { editorBridge } from \"./superblocks-editor-bridge.js\";\nimport type { IframeEventHandler } from \"../lib/internal-details/lib/iframe.js\";\n\n/** Timeout for waiting for APIs to become idle before capturing screenshot */\nconst WAIT_FOR_APIS_TIMEOUT_MS = 10_000;\n\n/**\n * Handles screenshot capture requests from the parent editor.\n * Only available in edit mode - modern-screenshot is not bundled in deployed apps.\n */\nexport function initializeScreenshotHandler() {\n if (!isEditMode()) {\n // Don't register handler in non-edit mode\n return;\n }\n\n const handleCaptureScreenshot: IframeEventHandler<\n \"capture-screenshot\"\n > = async ({ data }) => {\n const { callbackId, captureLoadingState } = data.payload;\n\n try {\n // If captureLoadingState is true, skip waiting for APIs and capture immediately\n // (useful for capturing loading shimmers/skeletons)\n if (captureLoadingState) {\n console.log(\n \"[Library Screenshot Handler] captureLoadingState=true, skipping API wait and capturing immediately...\",\n );\n } else {\n console.log(\n \"[Library Screenshot Handler] Screenshot capture requested, waiting for APIs to become idle...\",\n );\n\n // Wait for in-flight API requests to complete before capturing\n // This ensures we don't capture loading states/skeletons\n const { timedOut } = await apiActivityTracker.waitForIdle(\n WAIT_FOR_APIS_TIMEOUT_MS,\n );\n if (timedOut) {\n console.warn(\n \"[Library Screenshot Handler] Proceeding with screenshot capture despite pending API requests (skipping extra delay)\",\n );\n } else {\n console.log(\n \"[Library Screenshot Handler] APIs are idle, waiting 1s for UI to settle...\",\n );\n\n // Wait 1 second after APIs are done for the UI to render the data\n // Only do this if we didn't time out - no point waiting more if APIs are still in flight\n await new Promise((resolve) => setTimeout(resolve, 1_000));\n\n console.log(\n \"[Library Screenshot Handler] 1s delay complete, proceeding with screenshot capture\",\n );\n }\n }\n\n // Dynamically import modern-screenshot only when this handler is called (edit mode only)\n // Modern bundlers (Rollup/esbuild) will create a separate chunk for this import\n // Since initializeScreenshotHandler() returns early in non-edit mode,\n // this import() is never executed in deployed apps, so the chunk is never loaded\n const { domToWebp } = await import(\"modern-screenshot\");\n\n console.log(\"[Library Screenshot Handler] Capturing screenshot now...\");\n\n // Capture screenshot of the document body\n const dataUrl = await domToWebp(document.body, {\n backgroundColor: \"#ffffff\",\n });\n\n console.log(\n \"[Library Screenshot Handler] Screenshot captured successfully\",\n );\n\n // Send response back to parent\n editorBridge.sendCaptureScreenshotResponse(callbackId, dataUrl);\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n console.error(\n \"[Library Screenshot Handler] Error capturing screenshot:\",\n errorMessage,\n error,\n );\n\n // Send error response back to parent\n editorBridge.sendCaptureScreenshotResponse(\n callbackId,\n undefined,\n errorMessage,\n );\n }\n };\n\n // Register the handler\n iframeMessageHandler.addEventListener(\n \"capture-screenshot\",\n handleCaptureScreenshot,\n );\n}\n","import {\n AiGenerationState,\n ViteMessageKind,\n type SbElement,\n} from \"@superblocksteam/library-shared/types\";\nimport { observer } from \"mobx-react-lite\";\nimport React, { useEffect, useMemo, useRef, useState } from \"react\";\nimport { generatePath, useLocation, useNavigate } from \"react-router\";\nimport { handleBootstrapResponse } from \"../lib/internal-details/handle-bootstrap-response.js\";\nimport { FullPageSpinner } from \"../lib/internal-details/internal-components/spinner.jsx\";\nimport { isEditMode } from \"../lib/internal-details/is-edit-mode.js\";\nimport ApiHmrTracker from \"../lib/internal-details/lib/features/api-hmr-tracker.js\";\nimport { useGetCurrentUserQuery } from \"../lib/internal-details/lib/features/injected-features.js\";\nimport {\n isEmbeddedBySuperblocksFirstParty,\n iframeMessageHandler,\n} from \"../lib/internal-details/lib/iframe.js\";\nimport rootStore from \"../lib/internal-details/lib/root-store.js\";\nimport { useSuperblocksContext } from \"../lib/internal-details/superblocks-context.js\";\nimport { getApiPath } from \"../lib/internal-details/use-api.js\";\nimport { generateId } from \"../lib/utils/generate-id.js\";\nimport { initTracerProviderWithOrigin } from \"../lib/utils.js\";\nimport { BuildErrorNotification } from \"./build-error-notification.jsx\";\nimport createComponent from \"./create-component.js\";\nimport { initializeEditStore } from \"./edit-store.js\";\nimport { EditorHotkeys } from \"./editor-hotkeys.jsx\";\nimport { getEditStore } from \"./get-edit-store.js\";\nimport { initializeScreenshotHandler } from \"./screenshot-handler.js\";\nimport sourceUpdateApi from \"./source-update-api.js\";\nimport { editorBridge } from \"./superblocks-editor-bridge.js\";\nimport type { IframeEventHandler } from \"../lib/internal-details/lib/iframe.js\";\nimport type { MessageAction } from \"../lib/user-facing/types.js\";\nimport type { SbSelector } from \"@superblocksteam/library-shared/types\";\n\nlet _setReloadKey: (fn: (currentKey: number) => number) => void;\n\n/**\n * Triggers an HMR-style reload by incrementing the reload key.\n * This causes React to remount all children without a full page reload.\n * @param sendReadyAfter - If true, sends sb-ready after the remount completes\n */\nfunction triggerHmrReload(sendReadyAfter: boolean = false) {\n ApiHmrTracker.dontSkipUntilNextReload();\n _setReloadKey((currentKey) => currentKey + 1);\n\n if (sendReadyAfter) {\n // Wait for React to finish re-rendering before signaling ready\n requestAnimationFrame(() => {\n requestAnimationFrame(() => {\n editorBridge.sendReady();\n });\n });\n }\n}\n\nif (import.meta.hot) {\n import.meta.hot.on(\"sb:force-remount-after-reload\", () => {\n ApiHmrTracker.dontSkipUntilNextReload();\n _setReloadKey?.((currentKey) => currentKey + 1);\n });\n}\n\nif (isEditMode()) {\n const setupInitializer = () => {\n if (!isEmbeddedBySuperblocksFirstParty()) {\n return;\n }\n\n const handleInit: IframeEventHandler<\"sb-init\"> = async ({ data }) => {\n // Initialize tracer provider before WebSocket connection\n if (data.payload.windowOriginUrl) {\n initTracerProviderWithOrigin(data.payload.windowOriginUrl);\n }\n\n initializeEditStore();\n\n const editStore = getEditStore();\n editorBridge.connected();\n rootStore.setEditStore(editStore);\n rootStore.notifyEditorRegistered();\n\n // Initialize screenshot handler (only in edit mode)\n initializeScreenshotHandler();\n\n const { aiState, interactionMode } = data.payload;\n if (\n aiState?.generationState &&\n (aiState.generationState === AiGenerationState.GENERATING ||\n aiState.generationState === AiGenerationState.DEBUGGING)\n ) {\n editStore.ai.startEditing();\n if (aiState.editingComponents) {\n editStore.ai.setEditingComponents(aiState.editingComponents);\n }\n }\n\n if (interactionMode) {\n editStore.setInteractionMode(interactionMode);\n }\n\n if (\n data.payload.sessionRecordingKey &&\n data.payload.userId &&\n data.payload.appId\n ) {\n editStore.startRecording({\n userId: data.payload.userId,\n appId: data.payload.appId,\n sessionRecordingKey: data.payload.sessionRecordingKey,\n });\n }\n\n try {\n await sourceUpdateApi.connect({\n peerId: data.payload.peerId,\n userId: data.payload.userId,\n authorization: data.payload.devServerAuthorization,\n applicationId: data.payload.appId,\n traceContext: data.payload.traceContext,\n connectionType: data.payload.connectionType,\n connectionTarget: data.payload.connectionTarget,\n });\n } catch (error) {\n console.error(\n \"Error connecting to internal socket from library\",\n error,\n );\n // This will close the iframe\n editorBridge.socketError(\n \"Error connecting to the remote dev server, please refresh the page\",\n );\n return;\n }\n };\n const handleTokenUpdate: IframeEventHandler<\"sb-update-token\"> = ({\n data,\n }) => {\n const { authorization } = data.payload;\n console.log(\n \"Received sb-update-token message from iframe\",\n authorization?.substring(0, 20),\n );\n sourceUpdateApi.updateAuthorization(authorization);\n };\n\n iframeMessageHandler.addEventListener(\"sb-init\", handleInit);\n iframeMessageHandler.addEventListener(\"sb-update-token\", handleTokenUpdate);\n };\n requestIdleCallback(setupInitializer);\n}\n\nconst IframeConnected = observer(function IframeConnected(\n props: React.PropsWithChildren,\n) {\n const [reloadKey, setReloadKey] = useState(0);\n _setReloadKey = setReloadKey;\n useEffect(() => {\n editorBridge.sendReady();\n }, []);\n // for drag and drop\n useEffect(() => {\n const handleDragStart: IframeEventHandler<\"dragstart\"> = () => {\n // TODO: implement drag start\n };\n iframeMessageHandler.addEventListener(\"dragstart\", handleDragStart);\n return () => {\n iframeMessageHandler.removeEventListener(\"dragstart\", handleDragStart);\n };\n }, []);\n\n // Console log capture and global error handlers\n useEffect(() => {\n if (!isEmbeddedBySuperblocksFirstParty()) {\n return;\n }\n\n // Store original console methods\n const originalConsole = {\n warn: console.warn,\n error: console.error,\n debug: console.debug,\n info: console.info,\n log: console.log,\n };\n\n // Debouncing: batch logs and send at most once per 100ms\n const pendingLogs: Array<{\n level: \"log\" | \"warn\" | \"error\" | \"info\" | \"debug\";\n args: any[];\n stack?: string;\n }> = [];\n let flushTimer: NodeJS.Timeout | null = null;\n\n // Efficient serialization with length limiting\n const serializeArg = (arg: any, maxLength = 5000): string => {\n if (arg === null) return \"null\";\n if (arg === undefined) return \"undefined\";\n\n const type = typeof arg;\n if (type === \"string\") return arg;\n if (type === \"number\" || type === \"boolean\") return String(arg);\n if (type === \"function\") return `[Function: ${arg.name || \"anonymous\"}]`;\n if (type === \"symbol\") return arg.toString();\n\n // For objects, use JSON.stringify with special type handling\n try {\n const result = JSON.stringify(arg, (_key, value) => {\n // Handle special types\n if (value instanceof Error) {\n return `Error: ${value.message}`;\n }\n if (value instanceof Date) {\n return value.toISOString();\n }\n if (value instanceof RegExp) {\n return value.toString();\n }\n if (typeof value === \"function\") {\n return `[Function: ${value.name || \"anonymous\"}]`;\n }\n return value;\n });\n\n // Truncate if too long\n if (result.length > maxLength) {\n return result.substring(0, maxLength) + \"... [truncated]\";\n }\n return result;\n } catch {\n return \"[Circular or non-serializable object]\";\n }\n };\n\n // Check if a stack trace indicates framework code\n const isFrameworkStack = (stack: string | undefined): boolean => {\n if (!stack) return false;\n\n const frameworkStackPatterns = [\n /\\/node_modules\\//i, // All npm dependencies\n /\\/packages\\/library\\//i, // All internal Superblocks library code\n ];\n\n const frames = stack\n .split(\"\\n\")\n .map((line) => line.trim())\n .filter(Boolean);\n\n if (frames.length === 0) {\n return false;\n }\n\n const isFrameworkFrame = (frame: string) =>\n frameworkStackPatterns.some((pattern) => pattern.test(frame));\n\n // Only treat the stack as framework-only if every frame matches the framework patterns.\n return frames.every(isFrameworkFrame);\n };\n\n // Patterns for framework/internal logs that should be filtered out\n const isFrameworkLog = (\n message: string,\n stack: string | undefined,\n ): boolean => {\n const frameworkPatterns = [\n /^\\[vite\\]/i, // Vite HMR logs\n /^Pinged library socket/i, // Internal socket pings\n /^\\[HMR\\]/i, // Hot module reload\n /^Download the React DevTools/i, // React DevTools spam\n /^\\[internal\\]/i, // Internal logs\n ];\n\n // Check message patterns\n if (frameworkPatterns.some((pattern) => pattern.test(message))) {\n return true;\n }\n\n // Check stack trace patterns\n return isFrameworkStack(stack);\n };\n\n const flushLogs = () => {\n if (pendingLogs.length === 0) return;\n\n const logsToSend = pendingLogs.splice(0); // Clear and get all pending\n flushTimer = null;\n\n logsToSend.forEach(({ level, args, stack }) => {\n try {\n // Serialize arguments efficiently\n const message = args.map(serializeArg).join(\" \");\n\n // Skip framework/internal logs (using both message and stack)\n if (isFrameworkLog(message, stack)) {\n return;\n }\n\n const logEntry = {\n id: generateId(),\n timestamp: Date.now(),\n level,\n message,\n stack,\n };\n\n // Send to AI service - server handles buffering\n editorBridge.sendConsoleLog(logEntry);\n } catch {\n // Silently fail to avoid infinite loops\n }\n });\n };\n\n const queueConsoleLog = (\n level: \"warn\" | \"error\" | \"debug\" | \"info\" | \"log\",\n args: any[],\n ) => {\n // Capture stack immediately to enable filtering\n let stack: string | undefined;\n const rawStack = new Error().stack;\n if (rawStack) {\n // Strip first 3 frames: Error line, queueConsoleLog, console.X\n const lines = rawStack.split(\"\\n\");\n stack = lines.length > 3 ? lines.slice(3).join(\"\\n\") : undefined;\n }\n\n pendingLogs.push({ level, args, stack });\n\n // Schedule flush if not already scheduled\n if (!flushTimer) {\n flushTimer = setTimeout(flushLogs, 100);\n }\n };\n\n // Monkey-patch console methods\n console.warn = (...args: any[]) => {\n originalConsole.warn(...args);\n queueConsoleLog(\"warn\", args);\n };\n\n console.error = (...args: any[]) => {\n originalConsole.error(...args);\n queueConsoleLog(\"error\", args);\n };\n\n console.debug = (...args: any[]) => {\n originalConsole.debug(...args);\n queueConsoleLog(\"debug\", args);\n };\n\n console.info = (...args: any[]) => {\n originalConsole.info(...args);\n queueConsoleLog(\"info\", args);\n };\n\n console.log = (...args: any[]) => {\n originalConsole.log(...args);\n queueConsoleLog(\"log\", args);\n };\n\n // Helper to safely serialize errors\n const serializeError = (error: any): string => {\n if (!error) return \"Unknown error\";\n\n // If it's already a string, return it\n if (typeof error === \"string\") return error;\n\n // Try .toString() first (works for Error objects)\n const strValue = error.toString?.();\n if (strValue && strValue !== \"[object Object]\") {\n return strValue;\n }\n\n // Fall back to JSON.stringify for plain objects\n try {\n return JSON.stringify(error);\n } catch {\n return String(error);\n }\n };\n\n // Global error handler for unhandled errors\n const handleGlobalError = (event: ErrorEvent) => {\n const errorData = {\n id: generateId(),\n timestamp: Date.now(),\n error: serializeError(event.error) || event.message,\n errorInfo: {\n componentStack: event.error?.stack || \"\",\n },\n identifier: undefined,\n };\n\n // Fallback if store not ready - log to console\n if (!rootStore.editStore?.ai) {\n originalConsole.error(\n \"[Lost runtime error - store not ready]\",\n errorData,\n );\n return;\n }\n\n rootStore.editStore.ai.handleRuntimeError(errorData);\n };\n\n // Global handler for unhandled promise rejections\n const handleUnhandledRejection = (event: PromiseRejectionEvent) => {\n const errorData = {\n id: generateId(),\n timestamp: Date.now(),\n error: serializeError(event.reason) || \"Unhandled promise rejection\",\n errorInfo: {\n componentStack: event.reason?.stack || \"\",\n },\n identifier: undefined,\n };\n\n // Fallback if store not ready - log to console\n if (!rootStore.editStore?.ai) {\n originalConsole.error(\n \"[Lost runtime error - store not ready]\",\n errorData,\n );\n return;\n }\n\n rootStore.editStore.ai.handleRuntimeError(errorData);\n };\n\n window.addEventListener(\"error\", handleGlobalError);\n window.addEventListener(\"unhandledrejection\", handleUnhandledRejection);\n\n // Cleanup\n return () => {\n // Clear any pending flush timer\n if (flushTimer) {\n clearTimeout(flushTimer);\n }\n\n // Restore console methods\n console.warn = originalConsole.warn;\n console.error = originalConsole.error;\n console.debug = originalConsole.debug;\n console.info = originalConsole.info;\n console.log = originalConsole.log;\n\n // Remove event listeners\n window.removeEventListener(\"error\", handleGlobalError);\n window.removeEventListener(\n \"unhandledrejection\",\n handleUnhandledRejection,\n );\n };\n }, []);\n\n // This is not a production-ready hack because it prevents all embedding\n const isPossiblyEditor = useMemo(isEmbeddedBySuperblocksFirstParty, []);\n\n const connectionStatus =\n rootStore.editStore?.connectionManager.connectionStatus;\n if (connectionStatus === \"pre-init\" || connectionStatus === \"connecting\") {\n return <FullPageSpinner />;\n }\n\n if (\n isPossiblyEditor &&\n rootStore.editStore?.isInitialized &&\n typeof window !== \"undefined\"\n ) {\n return <React.Fragment key={reloadKey}>{props.children}</React.Fragment>;\n }\n\n if (isEditMode()) {\n console.log(\"In edit mode, but editor has not initialized yet\");\n return null;\n }\n\n return <React.Fragment key={reloadKey}>{props.children}</React.Fragment>;\n});\n\nconst WithUserWrapper = (props: React.PropsWithChildren) => {\n const { data: currentUser, isLoading } = useGetCurrentUserQuery();\n\n if (isLoading) {\n return <FullPageSpinner />;\n }\n\n if (!currentUser) {\n return <div>No user found</div>;\n }\n\n return <>{props.children}</>;\n};\n\nconst Auth0Wrapper = (props: React.PropsWithChildren) => {\n return (\n <WithUserWrapper>\n <IframeConnected>{props.children}</IframeConnected>\n </WithUserWrapper>\n );\n};\n\nconst EmbedWrapper = (props: React.PropsWithChildren) => {\n const isRetrievingToken = useRef(false);\n const [error, setError] = useState<string | undefined>();\n const [isLoaded, setIsLoaded] = useState(false);\n\n const navigate = useNavigate();\n const superblocksContext = useSuperblocksContext();\n\n useEffect(() => {\n const maxRetries = 20;\n let retryCount = 0;\n let timeout: NodeJS.Timeout;\n\n const attemptBootstrap = () => {\n if (rootStore.apis.isInitialized()) {\n return;\n }\n\n if (retryCount < maxRetries) {\n retryCount++;\n\n window.parent.postMessage(\n {\n type: \"sb-editor-request-bootstrap\",\n },\n \"*\",\n );\n\n timeout = setTimeout(attemptBootstrap, 200);\n } else {\n setError(\"Token took too long to load after multiple retries\");\n }\n };\n\n timeout = setTimeout(attemptBootstrap, 200);\n return () => clearTimeout(timeout);\n }, []);\n\n useEffect(() => {\n const bootstrapResponseListener: IframeEventHandler<\n \"sb-bootstrap-response\"\n > = (event) => {\n try {\n handleBootstrapResponse(event);\n setIsLoaded(true);\n iframeMessageHandler.removeEventListener(\n \"sb-bootstrap-response\",\n bootstrapResponseListener,\n );\n } catch (e) {\n setError(e?.toString());\n }\n };\n iframeMessageHandler.addEventListener(\n \"sb-bootstrap-response\",\n bootstrapResponseListener,\n );\n\n const updateActiveAgentsListener: IframeEventHandler<\n \"sb-update-active-agents\"\n > = (event) => {\n rootStore.apis.agentUrls = event.data.payload.agentUrls;\n };\n iframeMessageHandler.addEventListener(\n \"sb-update-active-agents\",\n updateActiveAgentsListener,\n );\n\n const retrievePropertyPanelPropsListener: IframeEventHandler<\n \"sb-retrieve-property-panel-props\"\n > = (event) => {\n const sourceId = event.data.payload.sourceId as SbElement;\n\n const selectorIds =\n getEditStore().ui.getMostRelevantSelectorIdsForSourceId(sourceId);\n\n if (!sourceId || selectorIds.length === 0) {\n getEditStore().ui.setSelectedSourceIds([]);\n getEditStore().ui.setSelectedSelectorIds([]);\n getEditStore().ui.setFocusedIds(null);\n return;\n }\n\n const alreadySelected = getEditStore().ui.isSourceSelected(sourceId);\n if (!alreadySelected) {\n getEditStore().ui.setSelectedSourceIds([sourceId]);\n getEditStore().ui.setSelectedSelectorIds(Array.from(selectorIds));\n getEditStore().ui.setFocusedIds(Array.from(selectorIds)[0]);\n }\n getEditStore().propertiesPanelManager.trackPropertiesPanel(\n selectorIds[0],\n );\n };\n iframeMessageHandler.addEventListener(\n \"sb-retrieve-property-panel-props\",\n retrievePropertyPanelPropsListener,\n );\n\n const editOperationAcknowledgeListener: IframeEventHandler<\n \"sb-edit-operation-acknowledge\"\n > = (event) => {\n getEditStore().operationManager.acknowledgeEditOperation(\n event.data.payload,\n );\n };\n iframeMessageHandler.addEventListener(\n \"sb-edit-operation-acknowledge\",\n editOperationAcknowledgeListener,\n );\n\n const updatePropertyWithEffectsListener: IframeEventHandler<\n \"sb-update-property-with-effects\"\n > = (event) => {\n const payload = {\n sourceId: event.data.payload.sourceId as SbElement,\n updates: event.data.payload.updates,\n };\n const propUpdates =\n getEditStore().propertiesPanelManager.computeAndApplySideEffectsForPropertyUpdate(\n payload,\n );\n\n editorBridge.resolvePromise(event.data.payload.callbackId, propUpdates);\n editorBridge.resolvePromise(\n event.data.payload.callbackId,\n payload.updates,\n );\n\n Object.keys(propUpdates).forEach((sourceId) => {\n getEditStore().operationManager.writeRuntimeProperties(\n sourceId as SbElement,\n event.data.payload.transaction.id,\n propUpdates[sourceId as SbElement],\n );\n });\n getEditStore().operationManager.writeRuntimeProperties(\n payload.sourceId,\n event.data.payload.transaction.id,\n payload.updates,\n );\n };\n iframeMessageHandler.addEventListener(\n \"sb-update-property-with-effects\",\n updatePropertyWithEffectsListener,\n );\n\n const createComponentListener: IframeEventHandler<\n \"sb-create-component\"\n > = async (event) => {\n const {\n componentType,\n parent,\n scopeName,\n baseProperties,\n skipSecondaryComponentsCreation,\n otherComponentsUpdates,\n } = event.data.payload;\n\n try {\n await createComponent({\n componentType,\n parent,\n scopeName,\n baseProperties,\n skipSecondaryComponentsCreation,\n otherComponentsUpdates,\n });\n } catch (error) {\n console.error(\"Failed to create component:\", error);\n }\n };\n iframeMessageHandler.addEventListener(\n \"sb-create-component\",\n createComponentListener,\n );\n\n const setInteractionModeListener: IframeEventHandler<\n \"set-interaction-mode\"\n > = async (event) => {\n const { interactionMode } = event.data.payload;\n rootStore.editStore?.setInteractionMode(interactionMode);\n };\n iframeMessageHandler.addEventListener(\n \"set-interaction-mode\",\n setInteractionModeListener,\n );\n\n const globalSyncListener: IframeEventHandler<\"sb-global-sync\"> = (\n event,\n ) => {\n const { global } = event.data.payload;\n superblocksContext.updateContext(global);\n };\n iframeMessageHandler.addEventListener(\"sb-global-sync\", globalSyncListener);\n\n const navigateToListener: IframeEventHandler<\"route-change\"> = async (\n event,\n ) => {\n const { route, routeParams, queryParams } = event.data.payload;\n\n const eventSearch = new URLSearchParams(queryParams);\n const nextSearch = new URLSearchParams(window.location.search);\n\n for (const [key, value] of eventSearch.entries()) {\n nextSearch.set(key, value);\n }\n\n await navigate({\n pathname: generatePath(route, routeParams),\n search: nextSearch.toString(),\n });\n };\n iframeMessageHandler.addEventListener(\"route-change\", navigateToListener);\n\n const aiUpdatesListener: IframeEventHandler<\"ai-updates\"> = (event) => {\n const { type } = event.data.payload;\n switch (type) {\n case \"start-editing\": {\n getEditStore().ai.startEditing();\n if (event.data.payload.components) {\n getEditStore().ai.setEditingComponents(\n event.data.payload.components,\n );\n }\n break;\n }\n case \"update-editing-entities\": {\n getEditStore().ai.setEditingComponents(event.data.payload.components);\n break;\n }\n case \"finish-editing\": {\n getEditStore().ai.finishEditing();\n break;\n }\n case \"set-ai-context-mode\": {\n const { mode, components } = event.data.payload;\n getEditStore().ai.setAiContextMode(mode, components);\n break;\n }\n case \"set-tagging-enabled\": {\n const { isTaggingEnabled } = event.data.payload;\n getEditStore().ai.setIsTaggingEnabled(isTaggingEnabled);\n break;\n }\n }\n };\n\n iframeMessageHandler.addEventListener(\"ai-updates\", aiUpdatesListener);\n\n const hmrReloadListener: IframeEventHandler<\"hmr-reload-request\"> = () => {\n triggerHmrReload(true);\n };\n\n iframeMessageHandler.addEventListener(\n \"hmr-reload-request\",\n hmrReloadListener,\n );\n\n return () => {\n iframeMessageHandler.removeEventListener(\n \"sb-bootstrap-response\",\n bootstrapResponseListener,\n );\n iframeMessageHandler.removeEventListener(\n \"sb-update-active-agents\",\n updateActiveAgentsListener,\n );\n iframeMessageHandler.removeEventListener(\n \"sb-edit-operation-acknowledge\",\n editOperationAcknowledgeListener,\n );\n iframeMessageHandler.removeEventListener(\n \"sb-update-property-with-effects\",\n updatePropertyWithEffectsListener,\n );\n iframeMessageHandler.removeEventListener(\n \"sb-retrieve-property-panel-props\",\n retrievePropertyPanelPropsListener,\n );\n iframeMessageHandler.removeEventListener(\n \"sb-create-component\",\n createComponentListener,\n );\n iframeMessageHandler.removeEventListener(\n \"sb-global-sync\",\n globalSyncListener,\n );\n iframeMessageHandler.removeEventListener(\n \"route-change\",\n navigateToListener,\n );\n iframeMessageHandler.removeEventListener(\"ai-updates\", aiUpdatesListener);\n iframeMessageHandler.removeEventListener(\n \"hmr-reload-request\",\n hmrReloadListener,\n );\n\n // Clear all runtime subscriptions on cleanup\n try {\n const editStore = getEditStore();\n editStore.runtimeSubscriptionsStore.clearAll();\n } catch {\n // EditStore might not be initialized yet\n }\n };\n }, [navigate, superblocksContext]);\n\n useEffect(() => {\n const messageListener = (event: MessageEvent) => {\n if (event.data?.type === \"parent-action-batch\" && event.data.payload) {\n event.data.payload.forEach((action: MessageAction) => {\n // TODO(code-mode): we ideally have a way to share this payload type from the editor, or\n // the editor should be able to import this type from the library\n switch (action.type) {\n case \"operations/editor:selectWidgets\": {\n const sourceIds: SbElement[] = action.payload.sourceIds;\n const selectorIdHint = action.payload.selectorIdHint;\n\n getEditStore().ui.setSelectedSourceIds(sourceIds);\n\n const selectorIds = sourceIds\n .flatMap((sourceId) => {\n // If we have a selectorIdHint and it matches this sourceId, use it\n if (selectorIdHint) {\n const component =\n getEditStore().runtimeTrackingStore.getComponent(\n selectorIdHint as SbSelector,\n );\n if (component?.sourceId === sourceId) {\n return [selectorIdHint as SbSelector];\n }\n }\n // Otherwise, use the default logic\n return getEditStore().ui.getMostRelevantSelectorIdsForSourceId(\n sourceId,\n );\n })\n .filter((selectorId) => selectorId !== null);\n getEditStore().ui.setSelectedSelectorIds(selectorIds);\n break;\n }\n case \"codeMode/cancelApiExecution\": {\n const { apiId } = action.payload;\n rootStore.apis.cancelApi(apiId);\n break;\n }\n case \"RUN_API\": {\n const { apiName, traceHeaders, callId, isTestRun, inputs } =\n action.payload;\n\n console.log(\"[iframe-wrappers] Received RUN_API:\", {\n apiName,\n callId,\n isTestRun,\n hasInputs: !!inputs,\n inputs,\n traceHeaders,\n });\n\n if (isTestRun) {\n console.log(\"[iframe-wrappers] Running as test run\");\n rootStore.apis\n .runApiByPath({\n path: getApiPath(apiName as never),\n inputs: { ...traceHeaders, ...inputs },\n isTestRun: true,\n })\n .catch((error) => {\n console.error(`Failed to test API ${apiName}:`, error);\n });\n } else if (callId) {\n console.log(\n \"[iframe-wrappers] Re-running with callId:\",\n callId,\n );\n // If callId is provided, this is a re-run request\n rootStore.apis.rerunApiByCallId(callId).catch((error) => {\n console.error(\n `Failed to re-run API with callId ${callId}:`,\n error,\n );\n });\n } else {\n console.log(\n \"[iframe-wrappers] This might be a Clark request - executing API normally\",\n );\n\n // Execute the API normally for Clark requests\n rootStore.apis\n .runApiByPath({\n path: getApiPath(apiName as never),\n inputs: { ...traceHeaders, ...inputs },\n callId,\n isTestRun: false,\n })\n .catch((error) => {\n console.error(`Failed to run API ${apiName}:`, error);\n });\n }\n\n break;\n }\n }\n });\n }\n };\n\n window.addEventListener(\"message\", messageListener);\n return () => window.removeEventListener(\"message\", messageListener);\n }, []);\n\n /**\n * This effect registers a listener that's called by the Vite dev server\n * after creating a new page. This helps us avoid race conditions by first\n * waiting for the page to be fully loaded and registered in the router\n * before attempting to navigate to it.\n * */\n const location = useLocation();\n useEffect(() => {\n try {\n const editStore = getEditStore();\n return editStore.onViteMessage(\n ViteMessageKind.ROUTE_CHANGE,\n async (message) => {\n try {\n const { route, routeTestParams } = message;\n const path = generatePath(route, routeTestParams);\n await navigate({ pathname: path, search: location.search });\n } catch (error) {\n throw new Error(`Failed to navigate to route: ${error}`);\n }\n },\n );\n } catch {\n return;\n }\n }, [navigate, location, isLoaded]);\n\n if (!isLoaded && error) {\n return (\n <div>\n <h3>There was an error logging in to Superblocks.</h3>\n <p>{error}</p>\n </div>\n );\n }\n\n if (!rootStore.apis.isInitialized() && !isLoaded) {\n if (!isRetrievingToken.current && window.parent !== window.self) {\n window.parent.postMessage(\n {\n type: \"sb-editor-request-bootstrap\",\n },\n \"*\",\n );\n isRetrievingToken.current = true;\n }\n\n return <FullPageSpinner />;\n }\n\n return (\n <WithUserWrapper>\n <IframeConnected>\n <BuildErrorNotification />\n <EditorHotkeys>{props.children}</EditorHotkeys>\n </IframeConnected>\n </WithUserWrapper>\n );\n};\n\nexport { EmbedWrapper, Auth0Wrapper };\n","export function throttle<T extends (...args: any[]) => any>(\n func: T,\n delay: number,\n): ((...args: Parameters<T>) => void) & { cancel: () => void } {\n let timeoutId: ReturnType<typeof setTimeout>;\n let lastExecTime = 0;\n\n const throttled = function (this: any, ...args: Parameters<T>) {\n const currentTime = Date.now();\n\n if (currentTime - lastExecTime < delay) {\n clearTimeout(timeoutId);\n timeoutId = setTimeout(() => {\n lastExecTime = currentTime;\n func.apply(this, args);\n }, delay);\n } else {\n lastExecTime = currentTime;\n func.apply(this, args);\n }\n };\n\n throttled.cancel = () => {\n clearTimeout(timeoutId);\n };\n\n return throttled;\n}\n\nexport function debounce<T extends (...args: any[]) => any>(\n func: T,\n delay: number,\n): (...args: Parameters<T>) => void {\n let timeoutId: ReturnType<typeof setTimeout>;\n\n return function (this: any, ...args: Parameters<T>) {\n clearTimeout(timeoutId);\n timeoutId = setTimeout(() => {\n func.apply(this, args);\n }, delay);\n };\n}\n","export const EXTENDED_CLICKABLE_AREA_DELTA = 6;\n\nexport const EXTENDED_CLICKABLE_ANCHOR_CSS = {\n top: `calc(anchor(top) - ${EXTENDED_CLICKABLE_AREA_DELTA}px)`,\n left: `calc(anchor(left) - ${EXTENDED_CLICKABLE_AREA_DELTA}px)`,\n right: `calc(anchor(right) - ${EXTENDED_CLICKABLE_AREA_DELTA}px)`,\n bottom: `calc(anchor(bottom) - ${EXTENDED_CLICKABLE_AREA_DELTA}px)`,\n};\n\nexport const EXTENDED_CLICKABLE_ANCHOR_CLIP_PATH = `polygon(\n 0% 0%, 0% 100%, 100% 100%, 100% 0%,\n 0% 0%, ${EXTENDED_CLICKABLE_AREA_DELTA}px ${EXTENDED_CLICKABLE_AREA_DELTA}px, calc(100% - ${EXTENDED_CLICKABLE_AREA_DELTA}px) ${EXTENDED_CLICKABLE_AREA_DELTA}px, \n calc(100% - ${EXTENDED_CLICKABLE_AREA_DELTA}px) calc(100% - ${EXTENDED_CLICKABLE_AREA_DELTA}px), ${EXTENDED_CLICKABLE_AREA_DELTA}px calc(100% - ${EXTENDED_CLICKABLE_AREA_DELTA}px), ${EXTENDED_CLICKABLE_AREA_DELTA}px ${EXTENDED_CLICKABLE_AREA_DELTA}px\n )`;\n","import {\n NO_SELECT_ATTRIBUTE,\n SELECTOR_ID_ATTRIBUTE,\n} from \"@superblocksteam/library-shared\";\nimport rootStore from \"../../lib/internal-details/lib/root-store.js\";\nimport { EXTENDED_CLICKABLE_AREA_DELTA } from \"../extended-clickable-area.js\";\nimport { getEditStore } from \"../get-edit-store.js\";\nimport type { SbSelector } from \"@superblocksteam/library-shared/types\";\n\nconst enablePointerEventsOnDisabledElements = (\n rootElement: HTMLElement | null,\n): (() => void) => {\n const editStore = getEditStore();\n const disabledSelectorIds =\n editStore.runtimeTrackingStore.getDisabledComponents();\n const modifiedElements: Array<{\n element: HTMLElement;\n hadInlineStyle: boolean;\n originalValue: string;\n }> = [];\n\n for (const selectorId of disabledSelectorIds) {\n const renderedTag =\n editStore.runtimeTrackingStore.getFirstAnchorableTag(selectorId);\n const selectorToQuery = renderedTag ?? selectorId;\n\n const element = document.querySelector(\n `[${SELECTOR_ID_ATTRIBUTE}=\"${selectorToQuery}\"]`,\n ) as HTMLElement | null;\n\n if (element) {\n if (!rootElement || rootElement.contains(element)) {\n const computedPointerEvents = getComputedStyle(element).pointerEvents;\n\n if (computedPointerEvents !== \"auto\") {\n const hadInlineStyle = element.style.pointerEvents !== \"\";\n const originalValue = element.style.pointerEvents;\n\n modifiedElements.push({\n element,\n hadInlineStyle,\n originalValue,\n });\n\n element.style.pointerEvents = \"auto\";\n }\n }\n }\n }\n\n return () => {\n modifiedElements.forEach(({ element, hadInlineStyle, originalValue }) => {\n if (hadInlineStyle) {\n element.style.pointerEvents = originalValue;\n } else {\n element.style.removeProperty(\"pointer-events\");\n }\n });\n };\n};\n\nconst calculateWidgetsAtCursor = (params: {\n x: number;\n y: number;\n rootElement: HTMLElement | null;\n delta?: { x: number; y: number };\n}) => {\n const restorePointerEvents = enablePointerEventsOnDisabledElements(\n params.rootElement,\n );\n\n try {\n let elements = document.elementsFromPoint(params.x, params.y);\n if (params.delta) {\n elements = [\n ...document.elementsFromPoint(\n params.x - params.delta.x,\n params.y - params.delta.y,\n ),\n ...document.elementsFromPoint(\n params.x + params.delta.x,\n params.y + params.delta.y,\n ),\n ...document.elementsFromPoint(\n params.x - params.delta.x,\n params.y + params.delta.y,\n ),\n ...document.elementsFromPoint(\n params.x + params.delta.x,\n params.y - params.delta.y,\n ),\n ];\n }\n const hoveredPills: { selectorId: SbSelector; noSelect?: boolean }[] = [];\n const hoveredActual: { selectorId: SbSelector; noSelect?: boolean }[] = [];\n\n new Set(elements).forEach((element) => {\n if (params.rootElement && !params.rootElement.contains(element)) {\n return; // Skip elements not within the rootElement\n }\n\n const selectorIdFromActual = element.getAttribute(SELECTOR_ID_ATTRIBUTE);\n if (selectorIdFromActual) {\n hoveredActual.push({\n selectorId: selectorIdFromActual as SbSelector,\n noSelect: element.hasAttribute(NO_SELECT_ATTRIBUTE),\n });\n } else {\n const selectorIdFromPill = element.getAttribute(\n \"data-sb-actions-selector-id\",\n );\n if (selectorIdFromPill) {\n hoveredPills.push({\n selectorId: selectorIdFromPill as SbSelector,\n });\n }\n }\n });\n\n return {\n hoveredPills,\n hoveredActual,\n };\n } finally {\n restorePointerEvents();\n }\n};\n\nconst getFirstItemWithFocusedSelectorPrioritized = (\n widgets: Array<{ selectorId: SbSelector; noSelect?: boolean }>,\n): { selectorId: SbSelector; noSelect?: boolean } | undefined => {\n const focusedSelectorId = getEditStore().ui.getFocusedSelectorId();\n if (focusedSelectorId) {\n const focusedPill = widgets.find((item) => {\n return item.selectorId === focusedSelectorId;\n });\n if (focusedPill) {\n return focusedPill;\n }\n }\n return widgets[0];\n};\n\n/*\n * First try to find a widget with an extended click area (only select if the widget has extended click area configured)\n * Then try to find a widget at the exact cursor position\n * Prioritize name pills over the underlying component\n */\nconst getWidgetFromPointHelper = (params: {\n x: number;\n y: number;\n rootElement: HTMLElement | null;\n}): { selectorId: SbSelector; noSelect?: boolean } | undefined => {\n const { x, y, rootElement } = params;\n const widgetsWithBuffer = calculateWidgetsAtCursor({\n x,\n y,\n rootElement,\n delta: {\n x: EXTENDED_CLICKABLE_AREA_DELTA,\n y: EXTENDED_CLICKABLE_AREA_DELTA,\n },\n });\n\n if (widgetsWithBuffer.hoveredPills.length > 0) {\n return getFirstItemWithFocusedSelectorPrioritized(\n widgetsWithBuffer.hoveredPills,\n );\n }\n\n const editStore = getEditStore();\n const extendedWidget = widgetsWithBuffer.hoveredActual.find((item) => {\n let actualSelectorId: SbSelector | undefined = item.selectorId;\n if (item.noSelect) {\n actualSelectorId =\n editStore.runtimeTrackingStore.getNearestSelectableAncestor(\n item.selectorId,\n false,\n );\n if (!actualSelectorId) {\n return false;\n }\n }\n const componentType =\n editStore.runtimeTrackingStore.getComponent(actualSelectorId)?.type;\n const editorConfig =\n rootStore.componentRegistry.getEditorConfigFromComponentType(\n componentType,\n );\n return editorConfig?.hasExtendedClickArea;\n });\n\n if (extendedWidget) {\n return extendedWidget;\n }\n\n const atPointWidgets = calculateWidgetsAtCursor({\n x,\n y,\n rootElement,\n });\n\n const firstWidget =\n getFirstItemWithFocusedSelectorPrioritized(atPointWidgets.hoveredPills) ??\n atPointWidgets.hoveredActual[0];\n\n return firstWidget;\n};\n\nconst shouldBubbleUpForNearestSelectableAncestor = (selectorId: SbSelector) => {\n const editStore = getEditStore();\n const widgetNode = editStore.runtimeTrackingStore.getComponent(selectorId);\n\n // New behavior: don't bubble based on noSelect anymore - we handle firstRenderedTag logic elsewhere\n // Only bubble if the widget itself is marked as an internal Superblocks component that shouldn't be directly selected\n const parentSelectorId =\n editStore.runtimeTrackingStore.getComponentParent(selectorId);\n if (!parentSelectorId) {\n return false;\n }\n const parentNode =\n editStore.runtimeTrackingStore.getComponent(parentSelectorId);\n\n // Only bubble if parent is an internal Superblocks component (not user-registered)\n // and current node is also an internal component\n return parentNode?.isSbComponent && widgetNode?.isSbComponent;\n};\n\n/**\n * This function will only return a new selector ID if and only if:\n * - The given instance represents a source ID with more than 1 instance on the page.\n * - The parent instance represents a source ID with FEWER instances than the given instance.\n * - The parent instance only contains 1 child (the given instance)\n *\n * Essentially, this should only ever \"narrow\" down the selection.\n * This is designed for situations where the user clicks on an HTML element that is heavily reused.\n * Example: components with some common styling.\n */\nconst getRelevantParentIfItReducesRepetition = (selectorId: SbSelector) => {\n const editStore = getEditStore();\n const component = editStore.runtimeTrackingStore.getComponent(selectorId);\n if (!component) {\n return undefined;\n }\n const allSelectorIdsForSourceId =\n editStore.runtimeTrackingStore.getSelectorIdsForSourceId(\n component.sourceId,\n );\n if (allSelectorIdsForSourceId.size <= 1) {\n return undefined;\n }\n const parentSelectorId =\n editStore.runtimeTrackingStore.getComponentParent(selectorId);\n const parentComponent = parentSelectorId\n ? editStore.runtimeTrackingStore.getComponent(parentSelectorId)\n : undefined;\n if (\n !parentComponent ||\n editStore.runtimeTrackingStore.getComponentChildren(parentSelectorId)\n .length !== 1\n ) {\n return undefined;\n }\n const parentSelectorIdsForSourceId =\n editStore.runtimeTrackingStore.getSelectorIdsForSourceId(\n parentComponent.sourceId,\n );\n if (parentSelectorIdsForSourceId.size < allSelectorIdsForSourceId.size) {\n return parentSelectorId;\n }\n return undefined;\n};\n\n/*\n * New selection algorithm:\n * 1. If the clicked element has data-no-select, bubble up to nearest selectable ancestor\n * 2. If the clicked element is the firstRenderedTag of a registered component, select that component\n * 3. Otherwise, select the HTML element itself (applying repetition reduction if helpful)\n * 4. Only bubble up for internal Superblocks components that shouldn't be directly selected\n */\nexport function getMostRelevantWidgetAtPoint(params: {\n x: number;\n y: number;\n rootElement: HTMLElement | null;\n}): SbSelector | undefined {\n const widget = getWidgetFromPointHelper(params);\n if (!widget) {\n return undefined;\n }\n const editStore = getEditStore();\n\n // If this element has data-no-select, bubble up to nearest selectable ancestor\n if (widget.noSelect) {\n const selectableAncestor =\n editStore.runtimeTrackingStore.getNearestSelectableAncestor(\n widget.selectorId,\n true, // skip self since self has no-select\n );\n if (selectableAncestor) {\n return selectableAncestor;\n }\n // If no selectable ancestor found, fall through to default behavior\n }\n\n // Check if this element is the root DOM element of a registered component\n // If so, select the outermost such component\n const componentForFirstRenderedTag =\n editStore.runtimeTrackingStore.getOutermostComponentForFirstRenderedTag(\n widget.selectorId,\n );\n if (componentForFirstRenderedTag) {\n return componentForFirstRenderedTag;\n }\n\n // If not the root of a registered component, try to reduce repetition for raw HTML elements\n const relevantParent = getRelevantParentIfItReducesRepetition(\n widget.selectorId,\n );\n if (relevantParent) {\n return relevantParent;\n }\n\n // Check if we need to bubble up for internal Superblocks components\n // IMPORTANT: Only bubble for non-HTML elements (internal Superblocks components)\n // HTML elements should always be selectable directly\n const widgetNode = editStore.runtimeTrackingStore.getComponent(\n widget.selectorId,\n );\n const isHtmlElement = widgetNode?.isHtmlElement;\n\n if (!isHtmlElement) {\n const bubbleUp = shouldBubbleUpForNearestSelectableAncestor(\n widget.selectorId,\n );\n if (bubbleUp) {\n const registeredAncestor =\n editStore.runtimeTrackingStore.getNearestSelectableAncestor(\n widget.selectorId,\n false,\n );\n if (registeredAncestor) {\n return registeredAncestor;\n }\n }\n }\n\n // Default: select the element itself\n return widget.selectorId;\n}\n","import { SELECTOR_ID_ATTRIBUTE } from \"@superblocksteam/library-shared\";\nimport { AiContextMode } from \"@superblocksteam/library-shared/types\";\nimport { observer } from \"mobx-react-lite\";\nimport React, { useCallback, useEffect, useState } from \"react\";\nimport ReactDOM from \"react-dom\";\nimport rootStore from \"../../lib/internal-details/lib/root-store.js\";\nimport { throttle } from \"../../lib/internal-details/lib/throttle.js\";\nimport { getEditStore } from \"../get-edit-store.js\";\nimport { editorBridge } from \"../superblocks-editor-bridge.js\";\nimport { getMostRelevantWidgetAtPoint } from \"./get-widgets-from-point.js\";\nimport {\n InteractionRect,\n selectDisplayNameAndVisibility,\n type SelectionInfo,\n useSelectionElements,\n} from \"./interaction-rect.jsx\";\n\nexport type RootType = \"App\" | \"Page\" | string;\n\nconst INTERACTION_LAYER_ATTRIBUTE = \"data-interaction-layer\";\n/**\n * Check if an element is an interaction layer container.\n */\nfunction isInteractionLayerContainer(element: Node): boolean {\n return (\n element instanceof HTMLElement &&\n element.getAttribute(INTERACTION_LAYER_ATTRIBUTE) === \"true\"\n );\n}\n\n/**\n * Get all direct children of body, excluding interaction layer containers.\n */\nfunction getBodyChildren(): HTMLElement[] {\n if (!document.body) {\n return [];\n }\n return Array.from(document.body.children).filter(\n (child) => !isInteractionLayerContainer(child),\n ) as HTMLElement[];\n}\n\n/**\n * Find the highest ancestor of an element that is a direct child of body.\n * Returns null if element is not in the document or has no body-child ancestor.\n */\nfunction getBodyChildAncestor(element: HTMLElement | null): HTMLElement | null {\n if (!element || !document.body) {\n return null;\n }\n\n let current: HTMLElement | null = element;\n while (current && current.parentElement !== document.body) {\n current = current.parentElement;\n }\n\n return current;\n}\n\n/**\n * Filter selection elements to only those that belong to the given container.\n * An element belongs to a container if its highest body-child ancestor matches the container.\n */\nfunction getElementsInScope(\n containerElement: HTMLElement,\n allElements: SelectionInfo[],\n editStore: ReturnType<typeof getEditStore>,\n): SelectionInfo[] {\n return allElements.filter((info) => {\n // Get the rendered tag for this selector\n const renderedTag = editStore.runtimeTrackingStore.getFirstAnchorableTag(\n info.selectorId,\n );\n const selectorToQuery = renderedTag ?? info.selectorId;\n\n // Find the DOM element\n const element = document.querySelector(\n `[${SELECTOR_ID_ATTRIBUTE}=\"${selectorToQuery}\"]`,\n ) as HTMLElement | null;\n\n if (!element) {\n return false;\n }\n\n // Find the highest body-child ancestor of this element\n const bodyChildAncestor = getBodyChildAncestor(element);\n\n // Element belongs to this container if its body-child ancestor matches\n return bodyChildAncestor === containerElement;\n });\n}\n\nfunction useWidgetHover() {\n const editStore = getEditStore();\n const interactionMode = editStore.interactionMode;\n const aiContextMode = editStore.ai.getAiContextMode();\n\n useEffect(() => {\n // Only enable hover in design mode or target mode (AUTO_SELECT)\n const isDesignMode = interactionMode === \"design\";\n const isTargetMode = aiContextMode === AiContextMode.AUTO_SELECT;\n\n if (!isDesignMode && !isTargetMode) {\n return;\n }\n\n const rootElement = document.body;\n const handleMouseMove = (event: MouseEvent) => {\n const selectorId = getMostRelevantWidgetAtPoint({\n x: event.clientX,\n y: event.clientY,\n rootElement,\n });\n if (selectorId) {\n editStore.ui.setFocusedIds(selectorId);\n }\n };\n\n const throttledHandleMouseMove = throttle(handleMouseMove, 25);\n const handleMouseLeave = () => {\n throttledHandleMouseMove.cancel();\n editStore.ui.setFocusedIds(null);\n };\n\n rootElement?.addEventListener(\"mousemove\", throttledHandleMouseMove);\n rootElement?.addEventListener(\"mouseleave\", handleMouseLeave);\n\n return () => {\n rootElement?.removeEventListener(\"mousemove\", throttledHandleMouseMove);\n rootElement?.removeEventListener(\"mouseleave\", handleMouseLeave);\n };\n }, [interactionMode, aiContextMode, editStore.ui]);\n}\n\nfunction useWidgetClick() {\n useEffect(() => {\n const rootElement = document.body;\n const editStore = getEditStore();\n\n const isInsideInteractionLayer = (element: EventTarget | null) => {\n if (!(element instanceof Element)) {\n return false;\n }\n return (\n element.closest(`[${INTERACTION_LAYER_ATTRIBUTE}=\"true\"]`) !== null\n );\n };\n\n const handleClick = (event: MouseEvent) => {\n if (event.defaultPrevented) {\n return;\n }\n\n if (!rootElement) {\n return;\n }\n\n // Don't handle clicks on interaction layer elements (name pills, action buttons)\n // Let them handle their own clicks\n if (isInsideInteractionLayer(event.target)) {\n return;\n }\n\n const selectorId = getMostRelevantWidgetAtPoint({\n x: event.clientX,\n y: event.clientY,\n rootElement,\n });\n if (!selectorId) {\n return;\n }\n\n // Get component info\n const component = editStore.runtimeTrackingStore.getComponent(selectorId);\n if (!component) {\n console.log(\n \"[internal] [useWidgetClick] No component found for selectorId\",\n );\n return;\n }\n\n const sourceId = component.sourceId;\n const { displayName } = selectDisplayNameAndVisibility(selectorId);\n\n const isTargettingComponent =\n editStore.ai.shouldToggleComponentInAiContext() || event.altKey;\n\n // do not propagate the click event when in design or target mode\n if (editStore.interactionMode === \"design\" || isTargettingComponent) {\n event.preventDefault();\n event.stopPropagation();\n }\n\n // Handle Alt key or AI tagging mode\n if (isTargettingComponent) {\n console.log(\n \"[internal] [useWidgetClick] Toggling component in AI context\",\n );\n editorBridge.toggleComponentInAiContext(\n sourceId,\n selectorId,\n displayName,\n );\n return;\n }\n editStore.ui.selectWidget(selectorId, event.shiftKey === true);\n };\n\n const handlePointerDown = (event: PointerEvent) => {\n const isTargetMode = editStore.ai.shouldToggleComponentInAiContext();\n\n if (\n (editStore.interactionMode === \"design\" || isTargetMode) &&\n !isInsideInteractionLayer(event.target)\n ) {\n event.preventDefault();\n event.stopPropagation();\n }\n };\n\n rootElement?.addEventListener(\"click\", handleClick, {\n capture: true,\n });\n rootElement?.addEventListener(\"pointerdown\", handlePointerDown, {\n capture: true,\n });\n\n return () => {\n rootElement?.removeEventListener(\"click\", handleClick, {\n capture: true,\n });\n rootElement?.removeEventListener(\"pointerdown\", handlePointerDown, {\n capture: true,\n });\n };\n }, []);\n}\n\ninterface InteractionLayerProps {\n containerElement: HTMLElement;\n layerId: string;\n}\n\nconst InteractionLayer = observer(\n ({ containerElement, layerId }: InteractionLayerProps) => {\n const editStore = getEditStore();\n const interactionMode = editStore.interactionMode;\n const allSelectedElements = useSelectionElements({\n focusedSourceId: editStore.ui.getFocusedSourceId(),\n focusedSelectorId: editStore.ui.getFocusedSelectorId(),\n selectedSelectorIds: editStore.ui.getSelectedSelectorIds(),\n selectedSourceIds: editStore.ui.getSelectedSourceIds(),\n targetedSourceIds: editStore.ai.getTargetedComponents(),\n aiContextMode: editStore.ai.getAiContextMode(),\n interactionMode,\n });\n\n // Filter elements to only those in this layer's scope\n const selectedElementsInScope = React.useMemo(\n () =>\n getElementsInScope(containerElement, allSelectedElements, editStore),\n [containerElement, allSelectedElements, editStore],\n );\n\n const isAiEditing = editStore.ai.getIsEditing();\n if (isAiEditing) {\n return null;\n }\n\n // Render interaction rects for elements in scope\n const interactionRectsForSelectedElements = selectedElementsInScope.map(\n (info, index) => {\n return (\n <InteractionRect\n key={info.selectorId + info.selectionType + index}\n {...info}\n />\n );\n },\n );\n\n // Create portal container and position it right after the container element\n const [portalContainer, setPortalContainer] =\n React.useState<HTMLElement | null>(null);\n\n useEffect(() => {\n const container = document.createElement(\"div\");\n container.className = `interaction-layer-container interaction-layer-${layerId}`;\n container.setAttribute(INTERACTION_LAYER_ATTRIBUTE, \"true\");\n container.style.cssText =\n \"position: fixed; overflow: hidden; z-index: 50; width: 0; height: 0; top: 0; left: 0;\";\n\n // Insert the portal container right after the container element\n const nextSibling = containerElement.nextSibling;\n if (nextSibling) {\n document.body.insertBefore(container, nextSibling);\n } else {\n document.body.appendChild(container);\n }\n\n setPortalContainer(container);\n\n return () => {\n container.remove();\n setPortalContainer(null);\n };\n }, [containerElement, layerId, editStore.interactionMode]);\n\n if (!portalContainer) {\n return null;\n }\n\n return ReactDOM.createPortal(\n <div\n style={\n interactionMode === \"design\"\n ? { \"--primary-rect-color\": \"#0BAD5C\" }\n : { \"--primary-rect-color\": \"#0087E0\" }\n }\n >\n {interactionRectsForSelectedElements}\n </div>,\n portalContainer,\n );\n },\n);\n\nconst InteractionLayerManager = observer(() => {\n useWidgetHover();\n useWidgetClick();\n\n const editStore = getEditStore();\n\n const handleCanvasClick = useCallback(() => {\n editorBridge.canvasClicked();\n }, []);\n\n useEffect(() => {\n window.addEventListener(\"click\", handleCanvasClick, true);\n return () => {\n window.removeEventListener(\"click\", handleCanvasClick, true);\n };\n }, [handleCanvasClick]);\n\n // Track all direct children of body (excluding interaction layer containers)\n const [bodyChildren, setBodyChildren] = useState<HTMLElement[]>(() => {\n return getBodyChildren();\n });\n\n // Observe body children changes\n useEffect(() => {\n if (!document.body) {\n return;\n }\n\n const updateBodyChildren = () => {\n setBodyChildren(getBodyChildren());\n };\n\n // Initial update\n updateBodyChildren();\n\n // Set up MutationObserver to watch for changes\n const observer = new MutationObserver((mutations) => {\n // Only update if the mutation is not from an interaction layer container being added/removed\n for (const mutation of mutations) {\n if (mutation.type === \"childList\") {\n const addedNodes = Array.from(mutation.addedNodes);\n const removedNodes = Array.from(mutation.removedNodes);\n const isInteractionLayerChange =\n addedNodes.some(isInteractionLayerContainer) ||\n removedNodes.some(isInteractionLayerContainer);\n\n // Only update if the change is not from our interaction layers\n if (!isInteractionLayerChange) {\n updateBodyChildren();\n break;\n }\n }\n }\n });\n\n observer.observe(document.body, { childList: true });\n\n return () => {\n observer.disconnect();\n };\n }, []);\n\n const isAiEditing = editStore.ai.getIsEditing();\n if (isAiEditing) {\n return null;\n }\n\n // Render one InteractionLayer for each body child\n return (\n <>\n {bodyChildren.map((child, index) => {\n const layerId = `layer-${index}-${child.tagName.toLowerCase()}`;\n return (\n <InteractionLayer\n key={layerId}\n containerElement={child}\n layerId={layerId}\n />\n );\n })}\n </>\n );\n});\n\n// Always-on context menu handler - runs even when interaction layer is not visible\nfunction useGlobalContextMenu() {\n useEffect(() => {\n const rootElement = document.body;\n\n const handleContextMenu = (event: MouseEvent) => {\n if (event.defaultPrevented) {\n return;\n }\n\n if (!rootElement) {\n return;\n }\n\n // Get fresh state from editStore\n const editStore = getEditStore();\n const isTargetMode = editStore.ai.shouldToggleComponentInAiContext();\n\n // Only show context menu when NOT in target mode\n if (isTargetMode) {\n return;\n }\n\n const selectorId = getMostRelevantWidgetAtPoint({\n x: event.clientX,\n y: event.clientY,\n rootElement,\n });\n\n if (!selectorId) {\n return;\n }\n\n const component = editStore.runtimeTrackingStore.getComponent(selectorId);\n if (!component) {\n return;\n }\n\n const sourceId = component.sourceId;\n\n event.preventDefault();\n event.stopPropagation();\n\n editorBridge.registerContextMenuClick(\n sourceId,\n selectorId,\n event.clientX,\n event.clientY,\n );\n };\n\n rootElement?.addEventListener(\"contextmenu\", handleContextMenu, {\n capture: true,\n });\n\n return () => {\n rootElement?.removeEventListener(\"contextmenu\", handleContextMenu, {\n capture: true,\n });\n };\n }, []);\n}\n\nconst ExternalInteractionLayer = observer(() => {\n const isEditStoreInitialized = Boolean(rootStore.editStore?.isInitialized);\n\n // Always run context menu handler, even when interaction layer is not visible\n useGlobalContextMenu();\n\n const isDesignMode = rootStore.editStore?.interactionMode === \"design\";\n const isTargetMode =\n rootStore.editStore?.ai.shouldToggleComponentInAiContext();\n const aiContextMode = rootStore.editStore?.ai.getAiContextMode();\n const isHighlightMode = aiContextMode === AiContextMode.HIGHLIGHT;\n\n // Also show interaction layer when there's a selected widget (for context menu)\n const hasSelectedWidget =\n (rootStore.editStore?.ui.getSelectedSourceIds().length ?? 0) > 0;\n\n // Show interaction layers in design mode, target mode, highlight mode, or when widget is selected\n const interactionLayerVisible =\n isDesignMode || isTargetMode || isHighlightMode || hasSelectedWidget;\n const shouldShowInteractionLayers =\n isEditStoreInitialized && interactionLayerVisible;\n if (!shouldShowInteractionLayers) {\n return null;\n }\n\n const pencilCursor = `url('data:image/svg+xml;utf8,<svg width=\"16\" height=\"16\" viewBox=\"0 0 16 16\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\"><path opacity=\"0.12\" d=\"M11.8703 5.81338C10.8293 5.47941 10.0738 4.50819 10.0626 3.35904L10.7109 2.71072C11.4229 1.99876 12.5772 1.99877 13.2892 2.71075C14.0011 3.42272 14.0011 4.57702 13.2892 5.28897L13.2083 5.36988C12.8412 5.73698 12.3436 5.9652 11.8703 5.81338Z\" fill=\"black\" stroke=\"black\" stroke-width=\"0.125\"/><path d=\"M10.0001 3.33308L4.18981 9.14329C3.6314 9.7017 3.25077 10.4129 3.0959 11.1873L2.66675 13.333L4.8125 12.9039C5.58686 12.749 6.29806 12.3684 6.85646 11.81L12.6667 5.99967M10.0001 3.33308L10.6668 2.66633C11.4032 1.92996 12.5971 1.92997 13.3335 2.66636V2.66636C14.0698 3.40273 14.0698 4.59661 13.3335 5.33297L12.6667 5.99967M10.0001 3.33308C10.0001 4.8058 11.194 5.99967 12.6667 5.99967\" stroke=\"white\" stroke-width=\"2.5\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/><path d=\"M10.0001 3.33308L4.18981 9.14329C3.6314 9.7017 3.25077 10.4129 3.0959 11.1873L2.66675 13.333L4.8125 12.9039C5.58686 12.749 6.29806 12.3684 6.85646 11.81L12.6667 5.99967M10.0001 3.33308L10.6668 2.66633C11.4032 1.92996 12.5971 1.92997 13.3335 2.66636V2.66636C14.0698 3.40273 14.0698 4.59661 13.3335 5.33297L12.6667 5.99967M10.0001 3.33308C10.0001 4.8058 11.194 5.99967 12.6667 5.99967\" stroke=\"black\" stroke-width=\"1.25\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/></svg>') 0 16, auto`;\n const targetCursor = `url('data:image/svg+xml;utf8,<svg width=\"16\" height=\"16\" viewBox=\"0 0 16 16\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\"><path opacity=\"0.12\" fill-rule=\"evenodd\" clip-rule=\"evenodd\" d=\"M14 8C14 11.3137 11.3137 14 8 14C4.68629 14 2 11.3137 2 8C2 4.68629 4.68629 2 8 2C11.3137 2 14 4.68629 14 8ZM8 9.26316C8.69762 9.26316 9.26316 8.69762 9.26316 8C9.26316 7.30238 8.69762 6.73684 8 6.73684C7.30238 6.73684 6.73684 7.30238 6.73684 8C6.73684 8.69762 7.30238 9.26316 8 9.26316Z\" fill=\"black\"/><path d=\"M14 8C14 11.3137 11.3137 14 8 14M14 8C14 4.68629 11.3137 2 8 2M14 8H12M8 14C4.68629 14 2 11.3137 2 8M8 14V12M2 8C2 4.68629 4.68629 2 8 2M2 8H4M8 2V4M9.26316 8C9.26316 8.69762 8.69762 9.26316 8 9.26316C7.30238 9.26316 6.73684 8.69762 6.73684 8C6.73684 7.30238 7.30238 6.73684 8 6.73684C8.69762 6.73684 9.26316 7.30238 9.26316 8Z\" stroke=\"white\" stroke-width=\"2.5\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/><path d=\"M14 8C14 11.3137 11.3137 14 8 14M14 8C14 4.68629 11.3137 2 8 2M14 8H12M8 14C4.68629 14 2 11.3137 2 8M8 14V12M2 8C2 4.68629 4.68629 2 8 2M2 8H4M8 2V4M9.26316 8C9.26316 8.69762 8.69762 9.26316 8 9.26316C7.30238 9.26316 6.73684 8.69762 6.73684 8C6.73684 7.30238 7.30238 6.73684 8 6.73684C8.69762 6.73684 9.26316 7.30238 9.26316 8Z\" stroke=\"black\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/></svg>') 8 8, auto`;\n\n let cursorStyle = \"\";\n if (isTargetMode) {\n cursorStyle = `* { cursor: ${targetCursor} !important; }`;\n } else if (isDesignMode) {\n cursorStyle = `* { cursor: ${pencilCursor} !important; }`;\n }\n\n return (\n <>\n <InteractionLayerManager />\n {cursorStyle && (\n <style\n dangerouslySetInnerHTML={{\n __html: cursorStyle,\n }}\n ></style>\n )}\n </>\n );\n});\n\nexport default ExternalInteractionLayer;\n","import React, { useEffect, useRef, useState } from \"react\";\nimport { generatePath, useNavigate } from \"react-router\";\nimport { handleBootstrapResponse } from \"./handle-bootstrap-response.js\";\nimport { FullPageSpinner } from \"./internal-components/spinner.jsx\";\nimport { useGetCurrentUserQuery } from \"./lib/features/injected-features.js\";\nimport { iframeMessageHandler } from \"./lib/iframe.js\";\nimport rootStore from \"./lib/root-store.js\";\nimport { useSuperblocksContext } from \"./superblocks-context.js\";\nimport type { IframeEventHandler } from \"./lib/iframe.js\";\nimport type { MessageAction } from \"../user-facing/types.js\";\n\nconst WithUserWrapper = (props: React.PropsWithChildren) => {\n const { data: currentUser, isLoading } = useGetCurrentUserQuery();\n\n if (isLoading) {\n return <FullPageSpinner />;\n }\n\n if (!currentUser) {\n return <div>No user found</div>;\n }\n\n return <>{props.children}</>;\n};\n\nconst Auth0Wrapper = (props: React.PropsWithChildren) => {\n return <WithUserWrapper>{props.children}</WithUserWrapper>;\n};\n\nconst EmbedWrapper = (props: React.PropsWithChildren) => {\n const isRetrievingToken = useRef(false);\n const [error, setError] = useState<string | undefined>();\n const [isLoaded, setIsLoaded] = useState(false);\n const navigate = useNavigate();\n const superblocksContext = useSuperblocksContext();\n\n useEffect(() => {\n const maxRetries = 20;\n let retryCount = 0;\n let timeout: NodeJS.Timeout;\n\n const attemptBootstrap = () => {\n if (rootStore.apis.isInitialized()) {\n return;\n }\n\n if (retryCount < maxRetries) {\n retryCount++;\n\n window.parent.postMessage(\n {\n type: \"sb-editor-request-bootstrap\",\n },\n \"*\",\n );\n\n timeout = setTimeout(attemptBootstrap, 200);\n } else {\n setError(\"Token took too long to load after multiple retries\");\n }\n };\n\n timeout = setTimeout(attemptBootstrap, 200);\n return () => clearTimeout(timeout);\n }, []);\n\n useEffect(() => {\n const bootstrapResponseListener: IframeEventHandler<\n \"sb-bootstrap-response\"\n > = (event) => {\n try {\n handleBootstrapResponse(event);\n setIsLoaded(true);\n iframeMessageHandler.removeEventListener(\n \"sb-bootstrap-response\",\n bootstrapResponseListener,\n );\n } catch (e) {\n setError(e?.toString());\n }\n };\n iframeMessageHandler.addEventListener(\n \"sb-bootstrap-response\",\n bootstrapResponseListener,\n );\n\n const globalSyncListener: IframeEventHandler<\"sb-global-sync\"> = (\n event,\n ) => {\n const { global } = event.data.payload;\n superblocksContext.updateContext(global);\n };\n iframeMessageHandler.addEventListener(\"sb-global-sync\", globalSyncListener);\n\n const navigateToListener: IframeEventHandler<\"route-change\"> = async (\n event,\n ) => {\n const { route, routeParams, queryParams } = event.data.payload;\n\n const eventSearch = new URLSearchParams(queryParams);\n const nextSearch = new URLSearchParams(window.location.search);\n\n for (const [key, value] of eventSearch.entries()) {\n nextSearch.set(key, value);\n }\n\n await navigate({\n pathname: generatePath(route, routeParams),\n search: nextSearch.toString(),\n });\n };\n iframeMessageHandler.addEventListener(\"route-change\", navigateToListener);\n\n return () => {\n iframeMessageHandler.removeEventListener(\n \"sb-bootstrap-response\",\n bootstrapResponseListener,\n );\n iframeMessageHandler.removeEventListener(\n \"sb-global-sync\",\n globalSyncListener,\n );\n iframeMessageHandler.removeEventListener(\n \"route-change\",\n navigateToListener,\n );\n };\n }, [navigate, superblocksContext]);\n\n useEffect(() => {\n const messageListener = (event: MessageEvent) => {\n if (event.data?.type === \"parent-action-batch\" && event.data.payload) {\n event.data.payload.forEach((action: MessageAction) => {\n // TODO(code-mode): we ideally have a way to share this payload type from the editor, or\n // the editor should be able to import this type from the library\n switch (action.type) {\n case \"RUN_API\": {\n // TODO: entityManager has been removed. API execution should now\n // go through rootStore.apis.runApiByPath or another method\n console.warn(\n \"RUN_API action is not supported without entityManager\",\n );\n break;\n }\n }\n });\n }\n };\n\n window.addEventListener(\"message\", messageListener);\n return () => window.removeEventListener(\"message\", messageListener);\n }, []);\n\n if (!isLoaded && error) {\n return (\n <div>\n <h3>There was an error logging in to Superblocks.</h3>\n <p>{error}</p>\n </div>\n );\n }\n\n if (!rootStore.apis.isInitialized() && !isLoaded) {\n if (!isRetrievingToken.current && window.parent !== window.self) {\n window.parent.postMessage(\n {\n type: \"sb-editor-request-bootstrap\",\n },\n \"*\",\n );\n isRetrievingToken.current = true;\n }\n\n return <FullPageSpinner />;\n }\n\n return <WithUserWrapper>{props.children}</WithUserWrapper>;\n};\n\nexport { EmbedWrapper, Auth0Wrapper };\n","import { Observer } from \"mobx-react-lite\";\nimport React from \"react\";\nimport { editorBridge } from \"../../../../edit-mode/superblocks-editor-bridge.js\";\nimport { isEditMode } from \"../../is-edit-mode.js\";\nimport rootStore from \"../../lib/root-store.js\";\nimport {\n ErrorIconContainer,\n StyledClarkIcon,\n ErrorTitle,\n ErrorMessage,\n ErrorDetails,\n ErrorSummary,\n ErrorStack,\n ErrorContainer,\n ErrorContent,\n SecondaryButton,\n ActionsContainer,\n} from \"../common.js\";\nimport { FixWithClarkButton } from \"../fix-with-clark-button.jsx\";\nimport type { LibUserAccessibleTheme } from \"../../../user-facing/themes/types.js\";\n\ninterface ErrorBoundaryState {\n hasError: boolean;\n error?: Error;\n}\n\ninterface ErrorBoundaryProps {\n children: React.ReactNode;\n theme?: LibUserAccessibleTheme;\n}\n\nexport class InternalErrorBoundary extends React.Component<\n ErrorBoundaryProps,\n ErrorBoundaryState\n> {\n constructor(props: ErrorBoundaryProps) {\n super(props);\n this.state = { hasError: false };\n }\n\n static getDerivedStateFromError(e: Error): ErrorBoundaryState {\n const error =\n e instanceof Error\n ? e\n : new Error(\n typeof e === \"object\" && e !== null ? JSON.stringify(e) : String(e),\n );\n return { hasError: true, error };\n }\n\n componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {\n console.error(\"Superblocks application error:\", error, errorInfo);\n if (isEditMode()) {\n editorBridge.sendLoadError(String(error));\n }\n }\n\n handleRefresh = () => {\n window.location.reload();\n };\n\n render() {\n if (this.state.hasError) {\n return (\n <Observer>\n {() => {\n // Check if AI is currently generating\n const isAIGenerating =\n rootStore.editStore?.ai.getIsEditing() ?? false;\n\n if (isAIGenerating) {\n // During AI generation, don't show error UI\n // Children already crashed, so just render nothing\n return null;\n }\n\n // When AI is not generating, show full error UI\n return (\n <ErrorContainer>\n <ErrorContent>\n <ErrorIconContainer>\n <StyledClarkIcon />\n </ErrorIconContainer>\n\n <ErrorTitle>Something went wrong</ErrorTitle>\n <ErrorMessage>\n {this.state.error?.message || \"Unknown error\"}\n </ErrorMessage>\n\n <ActionsContainer>\n {isEditMode() && (\n <FixWithClarkButton error={this.state.error} />\n )}\n <SecondaryButton onClick={this.handleRefresh}>\n Refresh page\n </SecondaryButton>\n </ActionsContainer>\n\n {this.state.error && (\n <ErrorDetails>\n <ErrorSummary>Full details</ErrorSummary>\n <ErrorStack>{this.state.error.stack}</ErrorStack>\n </ErrorDetails>\n )}\n </ErrorContent>\n </ErrorContainer>\n );\n }}\n </Observer>\n );\n }\n\n return this.props.children;\n }\n}\n","import React, { Suspense } from \"react\";\n\nlet internalStores: Record<string, any> = {};\n\nconst SUPPORTED_MODES = [\"local-dev\"];\n\nfunction registerStores(stores: Record<string, any>) {\n internalStores = { ...internalStores, ...stores };\n\n if (SUPPORTED_MODES.includes(import.meta.env.MODE)) {\n if (Object.keys(internalStores).length === Object.keys(stores).length) {\n import(\"./devtools-consolidated.jsx\")\n .then(({ initializeCustomDevTools, setRegisteredStores }) => {\n setRegisteredStores(internalStores);\n initializeCustomDevTools();\n })\n .catch((error) => {\n console.warn(\n \"[DevTools] Failed to initialize custom devtools:\",\n error,\n );\n });\n }\n }\n}\n\nconst DevToolsInternal = React.lazy(() => {\n return import(\"./devtools-consolidated.jsx\").then((module) => ({\n default: module.CustomDevTools,\n }));\n});\n\nconst DevTools = () => {\n if (!SUPPORTED_MODES.includes(import.meta.env.MODE)) {\n return null;\n }\n\n return (\n <Suspense fallback={null}>\n <DevToolsInternal />\n </Suspense>\n );\n};\n\nexport { DevTools, registerStores };\n","import equal from \"@superblocksteam/fast-deep-equal/es6\";\nimport { useContext, useEffect, useMemo, useRef } from \"react\";\nimport {\n UNSAFE_DataRouterContext,\n useLocation,\n useParams,\n type Location,\n} from \"react-router\";\nimport rootStore from \"./lib/root-store.js\";\n\nexport function useTrackRouteChange() {\n const routerContext = useContext(UNSAFE_DataRouterContext);\n const location = useLocation();\n const params = useParams();\n const prevLocation = useRef<Location>();\n\n const routes = useMemo(() => {\n if (!routerContext?.router.routes) return [];\n return routerContext?.router.routes;\n }, [routerContext?.router.routes]);\n\n useEffect(() => {\n if (!equal(location, prevLocation.current)) {\n rootStore.locationStore?.updateLocation(location, routes, params);\n // TODO: how do we decouple this routing change from the widget selection?\n rootStore.editStore?.ui.selectWidget(null);\n prevLocation.current = location;\n }\n }, [location, routes, params]);\n}\n","import { editorBridge } from \"../../edit-mode/superblocks-editor-bridge.js\";\nimport { isEditMode } from \"../internal-details/is-edit-mode.js\";\nimport rootStore from \"../internal-details/lib/root-store.js\";\n\nlet sbProviderRendered = false;\n\nexport const reportSbProviderRenderedEditMode = () => {\n sbProviderRendered = true;\n};\n\nconst ERROR_ID = \"base-app-not-rendered\";\n\nif (isEditMode()) {\n setTimeout(() => {\n if (!rootStore.editStore) {\n console.error(\"Edit store not initialized.\");\n }\n\n if (sbProviderRendered) {\n // in case this was fixed without us noticing it\n editorBridge.sendClearRuntimeError(ERROR_ID, true);\n return;\n }\n\n const errorMessage = `AppProvider not rendered in time.\nPlease ensure that 'App' from @superblocksteam/library is always rendered.\nAPI executions and editor features will be unavailable.\n`;\n console.error(errorMessage);\n editorBridge.sendRuntimeError(\n {\n id: ERROR_ID,\n error: errorMessage,\n errorInfo: {},\n },\n true,\n );\n editorBridge.sendLoadError(errorMessage);\n const intervalId = setInterval(() => {\n if (sbProviderRendered) {\n clearInterval(intervalId);\n editorBridge.sendClearRuntimeError(ERROR_ID, true);\n return;\n }\n }, 1000);\n }, 10_000);\n}\n","import { compile, middleware, prefixer, serialize, stringify } from \"stylis\";\n\nexport const VARIABLES: Record<string, string> = {\n primaryColor: \"--primary-color\",\n};\n\nconst VARIABLE_VALUES: Record<keyof typeof VARIABLES, string> = {\n primaryColor: \"blue\",\n};\n\nlet componentVariables: Record<string, string> = {};\nlet componentVariableValues: Record<string, string> = {};\n\nconst createStyleSheetFromString = (sheetId: string, styleSheet: string) => {\n const styles = serialize(\n compile(styleSheet),\n middleware([prefixer, stringify]),\n );\n const existingStyleTag = document.getElementById(sheetId);\n const styleTag = existingStyleTag ?? document.createElement(\"style\");\n styleTag.setAttribute(\"id\", sheetId);\n styleTag.replaceChildren(document.createTextNode(styles));\n if (existingStyleTag) return;\n document.head.appendChild(styleTag);\n};\n\nconst registry: Record<string, string> = {};\nexport const registerComponentStyle = (\n componentName: string,\n styleSheet: string,\n variableDefns: Record<string, string>,\n variableValues: Record<string, string>,\n) => {\n componentVariables = { ...componentVariables, ...variableDefns };\n componentVariableValues = { ...componentVariableValues, ...variableValues };\n const sheetId = `${componentName}-styles`;\n registry[sheetId] = styleSheet;\n};\n\nexport const initializeStyles = (appName: string) => {\n const stylesheet = Object.entries(registry)\n .map(([, styleSheet]) => styleSheet)\n .join(\"\\n\");\n const allVariables = { ...VARIABLES, ...componentVariables };\n const allVariableValues = { ...VARIABLE_VALUES, ...componentVariableValues };\n const variableDefns = Object.keys(allVariables)\n .map(\n (variable) =>\n `${allVariables[variable]}: ${allVariableValues[variable]};`,\n )\n .join(\"\\n\");\n createStyleSheetFromString(\n appName,\n `:${appName} {${variableDefns}}\\n${stylesheet}`,\n );\n};\n\nexport const MIN_EMPTY_WIDGET_SIZE = \"15px\";\n","import { getBindingIdentifier } from \"@superblocksteam/library-shared\";\nimport React, { useEffect, useState } from \"react\";\nimport {\n Auth0Wrapper as EditorAuth0Wrapper,\n EmbedWrapper as EditorEmbedWrapper,\n} from \"../../edit-mode/iframe-wrappers.jsx\";\nimport InteractionLayer from \"../../edit-mode/interaction-layer/interaction-layer.js\";\nimport {\n Auth0Wrapper as AppAuth0Wrapper,\n EmbedWrapper as AppEmbedWrapper,\n} from \"../internal-details/app-wrappers.jsx\";\nimport { InternalErrorBoundary } from \"../internal-details/internal-components/error-boundary/index.jsx\";\nimport { FullPageSpinner } from \"../internal-details/internal-components/spinner.js\";\nimport { isEditMode } from \"../internal-details/is-edit-mode.js\";\nimport { DevTools } from \"../internal-details/lib/devtools/index.jsx\";\nimport {\n iframeMessageHandler,\n type IframeEventHandler,\n} from \"../internal-details/lib/iframe.js\";\nimport {\n rejectById,\n resolveById,\n} from \"../internal-details/lib/resolve-id-singleton.js\";\nimport rootStore from \"../internal-details/lib/root-store.js\";\nimport { useTrackRouteChange } from \"../internal-details/routing.js\";\nimport { SuperblocksContextProvider } from \"../internal-details/superblocks-context.js\";\nimport { initializeCSSVariables } from \"./properties-panel/mixins/extract-variables.js\";\nimport { reportSbProviderRenderedEditMode } from \"./sb-provider-tracker.js\";\nimport { initializeStyles } from \"./styling/styles.js\";\nimport type { SuperblocksAppContext } from \"../internal-details/superblocks-context.js\";\n\nconst originalLog = console.log;\n\nconsole.log = (...args) => {\n try {\n const processedArgs = args.map((arg) => {\n if (\n arg &&\n typeof arg === \"object\" &&\n (getBindingIdentifier(arg) || getBindingIdentifier(arg.bind ?? {}))\n ) {\n return JSON.parse(JSON.stringify(arg));\n }\n return arg;\n });\n originalLog(...processedArgs);\n } catch {\n // Do nothing\n }\n};\n\nconst loadApisIntoLibrary = async function loadApisIntoLibrary() {\n if (!isEditMode()) {\n try {\n const mod = await import(\"./build-manifest.js\");\n rootStore.apis.loadApiManifest(mod.default);\n } catch (error) {\n console.error(\"Error loading apis into library\", error);\n }\n }\n};\n\nconst Auth0Wrapper = isEditMode() ? EditorAuth0Wrapper : AppAuth0Wrapper;\nconst EmbedWrapper = isEditMode() ? EditorEmbedWrapper : AppEmbedWrapper;\n\nconst SbProvider = function SbProvider({\n name = \"codemode\",\n children,\n className,\n context,\n}: {\n name?: string;\n children?: React.ReactNode;\n className?: string;\n context?: SuperblocksAppContext;\n}) {\n const isEmbedded =\n typeof window !== \"undefined\" && window.parent !== window.self;\n\n useTrackRouteChange();\n\n const [isApisInitialized, setIsApisInitialized] = useState(false);\n useEffect(() => {\n (async () => {\n await loadApisIntoLibrary();\n setIsApisInitialized(true);\n })();\n }, []);\n\n useEffect(() => {\n const resolvePromiseListener: IframeEventHandler<\"resolve-promise\"> = (\n event,\n ) => {\n resolveById(event.data.callbackId, event.data.payload);\n };\n\n const rejectPromiseListener: IframeEventHandler<\"reject-promise\"> = (\n event,\n ) => {\n rejectById(event.data.callbackId, event.data.payload);\n };\n\n // These handlers need to be here instead of on the iframe wrappers because\n // we need the promise resolution on the API set before we render the iframe wrapper\n iframeMessageHandler.addEventListener(\n \"resolve-promise\",\n resolvePromiseListener,\n );\n iframeMessageHandler.addEventListener(\n \"reject-promise\",\n rejectPromiseListener,\n );\n return () => {\n iframeMessageHandler.removeEventListener(\n \"resolve-promise\",\n resolvePromiseListener,\n );\n iframeMessageHandler.removeEventListener(\n \"reject-promise\",\n rejectPromiseListener,\n );\n };\n }, []);\n\n useEffect(() => {\n initializeStyles(name);\n }, [name]);\n\n // if in edit mode, try to extract css variables and report that we're rendered\n useEffect(() => {\n if (isEditMode()) {\n initializeCSSVariables();\n reportSbProviderRenderedEditMode();\n }\n }, []);\n\n if (!isApisInitialized) {\n return <FullPageSpinner />;\n }\n\n return (\n <div id=\"sb-provider-root\" className={className}>\n <InternalErrorBoundary>\n <div className=\"h-full w-full relative\">\n <SuperblocksContextProvider value={context ?? undefined}>\n {isEmbedded ? (\n <EmbedWrapper>{children}</EmbedWrapper>\n ) : (\n <Auth0Wrapper>{children}</Auth0Wrapper>\n )}\n </SuperblocksContextProvider>\n <DevTools />\n </div>\n </InternalErrorBoundary>\n <InteractionLayer />\n </div>\n );\n};\n\nexport default SbProvider;\n","import type { EditorConfig } from \"@superblocksteam/library-shared/types\";\n\nexport const editorConfig: EditorConfig = {\n icon: \"app\",\n isDraggable: false,\n};\n","import { tailwindStylesCategory } from \"../../properties-panel/mixins/styles-category.js\";\nimport {\n Prop,\n PropsCategory,\n Section,\n} from \"../../properties-panel/props-builder.js\";\n\nexport const propertiesDefinition = {\n contents: Section.category(PropsCategory.Content).children({\n children: Prop.jsx(),\n }),\n appearance: tailwindStylesCategory(),\n};\n","import { NATIVE_COMPONENT_TYPES } from \"@superblocksteam/library-shared\";\nimport { observer } from \"mobx-react-lite\";\nimport { registerComponentInternal } from \"../../internal-index.js\";\nimport SuperblocksProvider from \"../../sb-provider.jsx\";\nimport { editorConfig } from \"./editor.js\";\nimport { propertiesDefinition } from \"./props.js\";\nimport type { SuperblocksAppContext } from \"../../../internal-details/superblocks-context.js\";\nimport type { InternalProps } from \"../../properties-panel/props-builder.js\";\n\nconst App = observer(\n ({\n children,\n className,\n context,\n }: InternalProps<typeof propertiesDefinition> & {\n context?: SuperblocksAppContext;\n }) => {\n return (\n <SuperblocksProvider name=\"App\" className={className} context={context}>\n {children}\n </SuperblocksProvider>\n );\n },\n);\nApp.displayName = NATIVE_COMPONENT_TYPES.App;\n\nregisterComponentInternal(App, propertiesDefinition).editorConfig(editorConfig);\n\nexport { App };\n","export enum API_STATUS_CODES {\n REQUEST_UNAUTHORIZED = 401,\n RESOURCE_FORBIDDEN = 403,\n RESOURCE_NOT_FOUND = 404,\n TIMEOUT = 408,\n RESOURCE_CONFLICT = 409,\n SERVER_ERROR = 502,\n SERVER_UNAVAILABLE = 503,\n BAD_REQUEST = 400,\n}\n","<svg width=\"167\" height=\"168\" viewBox=\"0 0 167 168\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\">\n<g filter=\"url(#filter0_i_1_117)\">\n<g clip-path=\"url(#clip0_1_117)\">\n<rect width=\"164\" height=\"164\" rx=\"82\" fill=\"#F9FAFB\"/>\n<g filter=\"url(#filter1_dd_1_117)\">\n<g clip-path=\"url(#clip1_1_117)\">\n<rect x=\"32\" y=\"36\" width=\"256\" height=\"140\" rx=\"6\" fill=\"white\"/>\n<rect width=\"132\" height=\"12\" transform=\"translate(32 36)\" fill=\"#454D5F\"/>\n<circle opacity=\"0.24\" cx=\"39\" cy=\"42\" r=\"3\" fill=\"white\"/>\n<rect opacity=\"0.24\" x=\"46\" y=\"41\" width=\"10\" height=\"2\" rx=\"1\" fill=\"white\"/>\n<rect x=\"44\" y=\"60\" width=\"104\" height=\"36\" rx=\"4\" fill=\"#F3F4F6\"/>\n<rect x=\"44\" y=\"104\" width=\"48\" height=\"36\" rx=\"4\" fill=\"#F3F4F6\"/>\n<rect x=\"44\" y=\"148\" width=\"48\" height=\"36\" rx=\"4\" fill=\"#F3F4F6\"/>\n<rect x=\"100\" y=\"104\" width=\"48\" height=\"36\" rx=\"4\" fill=\"#F3F4F6\"/>\n<rect x=\"100\" y=\"148\" width=\"48\" height=\"36\" rx=\"4\" fill=\"#F3F4F6\"/>\n</g>\n</g>\n</g>\n</g>\n<g filter=\"url(#filter2_d_1_117)\">\n<rect x=\"108\" y=\"108\" width=\"56\" height=\"56\" rx=\"28\" fill=\"white\" shape-rendering=\"crispEdges\"/>\n<circle cx=\"136\" cy=\"136\" r=\"23.5\" fill=\"#F9FAFB\" stroke=\"#C6CAD2\" stroke-dasharray=\"4 4\"/>\n<path opacity=\"0.2\" d=\"M143.5 132.25H128.5C128.086 132.25 127.75 132.586 127.75 133V143.5C127.75 143.914 128.086 144.25 128.5 144.25H143.5C143.914 144.25 144.25 143.914 144.25 143.5V133C144.25 132.586 143.914 132.25 143.5 132.25Z\" fill=\"#6C7689\"/>\n<path d=\"M143.5 132.25H128.5C128.086 132.25 127.75 132.586 127.75 133V143.5C127.75 143.914 128.086 144.25 128.5 144.25H143.5C143.914 144.25 144.25 143.914 144.25 143.5V133C144.25 132.586 143.914 132.25 143.5 132.25Z\" stroke=\"#6C7689\" stroke-width=\"1.25\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/>\n<path d=\"M132.625 132.25V128.875C132.625 127.98 132.981 127.121 133.614 126.489C134.246 125.856 135.105 125.5 136 125.5C136.895 125.5 137.754 125.856 138.386 126.489C139.019 127.121 139.375 127.98 139.375 128.875V132.25\" stroke=\"#6C7689\" stroke-width=\"1.25\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/>\n<path d=\"M136 139.375C136.621 139.375 137.125 138.871 137.125 138.25C137.125 137.629 136.621 137.125 136 137.125C135.379 137.125 134.875 137.629 134.875 138.25C134.875 138.871 135.379 139.375 136 139.375Z\" fill=\"#6C7689\"/>\n</g>\n<defs>\n<filter id=\"filter0_i_1_117\" x=\"0\" y=\"-1\" width=\"164\" height=\"165\" filterUnits=\"userSpaceOnUse\" color-interpolation-filters=\"sRGB\">\n<feFlood flood-opacity=\"0\" result=\"BackgroundImageFix\"/>\n<feBlend mode=\"normal\" in=\"SourceGraphic\" in2=\"BackgroundImageFix\" result=\"shape\"/>\n<feColorMatrix in=\"SourceAlpha\" type=\"matrix\" values=\"0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0\" result=\"hardAlpha\"/>\n<feOffset dy=\"-1\"/>\n<feGaussianBlur stdDeviation=\"1.5\"/>\n<feComposite in2=\"hardAlpha\" operator=\"arithmetic\" k2=\"-1\" k3=\"1\"/>\n<feColorMatrix type=\"matrix\" values=\"0 0 0 0 0.1056 0 0 0 0 0.11904 0 0 0 0 0.1344 0 0 0 0.2 0\"/>\n<feBlend mode=\"normal\" in2=\"shape\" result=\"effect1_innerShadow_1_117\"/>\n</filter>\n<filter id=\"filter1_dd_1_117\" x=\"29\" y=\"34\" width=\"262\" height=\"146\" filterUnits=\"userSpaceOnUse\" color-interpolation-filters=\"sRGB\">\n<feFlood flood-opacity=\"0\" result=\"BackgroundImageFix\"/>\n<feColorMatrix in=\"SourceAlpha\" type=\"matrix\" values=\"0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0\" result=\"hardAlpha\"/>\n<feOffset/>\n<feGaussianBlur stdDeviation=\"1\"/>\n<feComposite in2=\"hardAlpha\" operator=\"out\"/>\n<feColorMatrix type=\"matrix\" values=\"0 0 0 0 0.0775545 0 0 0 0 0.0335371 0 0 0 0 0.206463 0 0 0 0.12 0\"/>\n<feBlend mode=\"normal\" in2=\"BackgroundImageFix\" result=\"effect1_dropShadow_1_117\"/>\n<feColorMatrix in=\"SourceAlpha\" type=\"matrix\" values=\"0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0\" result=\"hardAlpha\"/>\n<feOffset dy=\"1\"/>\n<feGaussianBlur stdDeviation=\"1.5\"/>\n<feComposite in2=\"hardAlpha\" operator=\"out\"/>\n<feColorMatrix type=\"matrix\" values=\"0 0 0 0 0.0775545 0 0 0 0 0.0335371 0 0 0 0 0.206463 0 0 0 0.04 0\"/>\n<feBlend mode=\"normal\" in2=\"effect1_dropShadow_1_117\" result=\"effect2_dropShadow_1_117\"/>\n<feBlend mode=\"normal\" in=\"SourceGraphic\" in2=\"effect2_dropShadow_1_117\" result=\"shape\"/>\n</filter>\n<filter id=\"filter2_d_1_117\" x=\"105\" y=\"106\" width=\"62\" height=\"62\" filterUnits=\"userSpaceOnUse\" color-interpolation-filters=\"sRGB\">\n<feFlood flood-opacity=\"0\" result=\"BackgroundImageFix\"/>\n<feColorMatrix in=\"SourceAlpha\" type=\"matrix\" values=\"0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0\" result=\"hardAlpha\"/>\n<feOffset dy=\"1\"/>\n<feGaussianBlur stdDeviation=\"1.5\"/>\n<feComposite in2=\"hardAlpha\" operator=\"out\"/>\n<feColorMatrix type=\"matrix\" values=\"0 0 0 0 0.1056 0 0 0 0 0.11904 0 0 0 0 0.1344 0 0 0 0.16 0\"/>\n<feBlend mode=\"normal\" in2=\"BackgroundImageFix\" result=\"effect1_dropShadow_1_117\"/>\n<feBlend mode=\"normal\" in=\"SourceGraphic\" in2=\"effect1_dropShadow_1_117\" result=\"shape\"/>\n</filter>\n<clipPath id=\"clip0_1_117\">\n<rect width=\"164\" height=\"164\" rx=\"82\" fill=\"white\"/>\n</clipPath>\n<clipPath id=\"clip1_1_117\">\n<rect x=\"32\" y=\"36\" width=\"256\" height=\"140\" rx=\"6\" fill=\"white\"/>\n</clipPath>\n</defs>\n</svg>\n","<svg width=\"164\" height=\"164\" viewBox=\"0 0 164 164\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\">\n<g filter=\"url(#filter0_i_4124_102997)\">\n<g clip-path=\"url(#clip0_4124_102997)\">\n<rect width=\"164\" height=\"164\" rx=\"82\" fill=\"#F9FAFB\"/>\n<g filter=\"url(#filter1_dd_4124_102997)\">\n<g clip-path=\"url(#clip1_4124_102997)\">\n<rect x=\"16\" y=\"48\" width=\"132\" height=\"124\" rx=\"4\" fill=\"white\"/>\n<rect width=\"132\" height=\"12\" transform=\"translate(16 48)\" fill=\"#454D5F\"/>\n<circle opacity=\"0.24\" cx=\"23\" cy=\"54\" r=\"3\" fill=\"white\"/>\n<rect opacity=\"0.24\" x=\"30\" y=\"53\" width=\"10\" height=\"2\" rx=\"1\" fill=\"white\"/>\n<g clip-path=\"url(#clip2_4124_102997)\">\n<rect width=\"132\" height=\"132\" transform=\"translate(16 60)\" fill=\"white\"/>\n<rect opacity=\"0.16\" x=\"40\" y=\"160\" width=\"16\" height=\"2\" rx=\"1\" fill=\"#454D5F\"/>\n<rect opacity=\"0.24\" x=\"120\" y=\"158\" width=\"6\" height=\"6\" rx=\"1.5\" fill=\"#454D5F\"/>\n<rect opacity=\"0.24\" x=\"24\" y=\"157\" width=\"8\" height=\"8\" rx=\"4\" fill=\"#454D5F\"/>\n</g>\n<path d=\"M68.8367 113.863V117.613H48.3289L48.1727 114.781L60.4383 95.5625H64.2078L60.1258 102.555L53.075 113.863H68.8367ZM65.282 95.5625V124H60.575V95.5625H65.282ZM91.3164 107.398V112.047C91.3164 114.273 91.0951 116.174 90.6523 117.75C90.2227 119.312 89.5977 120.582 88.7773 121.559C87.957 122.535 86.974 123.251 85.8281 123.707C84.6953 124.163 83.4258 124.391 82.0195 124.391C80.8997 124.391 79.8581 124.247 78.8945 123.961C77.944 123.674 77.0846 123.225 76.3164 122.613C75.5482 122.001 74.8906 121.214 74.3438 120.25C73.8099 119.273 73.3932 118.108 73.0938 116.754C72.8073 115.4 72.6641 113.831 72.6641 112.047V107.398C72.6641 105.159 72.8854 103.271 73.3281 101.734C73.7708 100.185 74.4023 98.9284 75.2227 97.9648C76.043 96.9883 77.0195 96.2786 78.1523 95.8359C79.2982 95.3932 80.5742 95.1719 81.9805 95.1719C83.1133 95.1719 84.1549 95.3151 85.1055 95.6016C86.069 95.875 86.9284 96.3112 87.6836 96.9102C88.4518 97.5091 89.1029 98.2904 89.6367 99.2539C90.1836 100.204 90.6003 101.357 90.8867 102.711C91.1732 104.052 91.3164 105.615 91.3164 107.398ZM86.6094 112.711V106.695C86.6094 105.562 86.5443 104.566 86.4141 103.707C86.2839 102.835 86.0885 102.099 85.8281 101.5C85.5807 100.888 85.2682 100.393 84.8906 100.016C84.513 99.625 84.0833 99.3451 83.6016 99.1758C83.1198 98.9935 82.5794 98.9023 81.9805 98.9023C81.2513 98.9023 80.6003 99.0456 80.0273 99.332C79.4544 99.6055 78.9727 100.048 78.582 100.66C78.1914 101.272 77.8919 102.079 77.6836 103.082C77.4883 104.072 77.3906 105.276 77.3906 106.695V112.711C77.3906 113.857 77.4557 114.866 77.5859 115.738C77.7161 116.611 77.9115 117.359 78.1719 117.984C78.4323 118.596 78.7448 119.104 79.1094 119.508C79.487 119.898 79.9167 120.185 80.3984 120.367C80.8932 120.549 81.4336 120.641 82.0195 120.641C82.7617 120.641 83.4193 120.497 83.9922 120.211C84.5651 119.924 85.0469 119.469 85.4375 118.844C85.8281 118.206 86.1211 117.379 86.3164 116.363C86.5117 115.348 86.6094 114.13 86.6094 112.711ZM115.905 113.863V117.613H95.3977L95.2414 114.781L107.507 95.5625H111.277L107.195 102.555L100.144 113.863H115.905ZM112.351 95.5625V124H107.644V95.5625H112.351Z\" fill=\"#C6CAD2\"/>\n</g>\n</g>\n</g>\n</g>\n<defs>\n<filter id=\"filter0_i_4124_102997\" x=\"0\" y=\"-1\" width=\"164\" height=\"165\" filterUnits=\"userSpaceOnUse\" color-interpolation-filters=\"sRGB\">\n<feFlood flood-opacity=\"0\" result=\"BackgroundImageFix\"/>\n<feBlend mode=\"normal\" in=\"SourceGraphic\" in2=\"BackgroundImageFix\" result=\"shape\"/>\n<feColorMatrix in=\"SourceAlpha\" type=\"matrix\" values=\"0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0\" result=\"hardAlpha\"/>\n<feOffset dy=\"-1\"/>\n<feGaussianBlur stdDeviation=\"1.5\"/>\n<feComposite in2=\"hardAlpha\" operator=\"arithmetic\" k2=\"-1\" k3=\"1\"/>\n<feColorMatrix type=\"matrix\" values=\"0 0 0 0 0.1056 0 0 0 0 0.11904 0 0 0 0 0.1344 0 0 0 0.2 0\"/>\n<feBlend mode=\"normal\" in2=\"shape\" result=\"effect1_innerShadow_4124_102997\"/>\n</filter>\n<filter id=\"filter1_dd_4124_102997\" x=\"13\" y=\"46\" width=\"138\" height=\"130\" filterUnits=\"userSpaceOnUse\" color-interpolation-filters=\"sRGB\">\n<feFlood flood-opacity=\"0\" result=\"BackgroundImageFix\"/>\n<feColorMatrix in=\"SourceAlpha\" type=\"matrix\" values=\"0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0\" result=\"hardAlpha\"/>\n<feOffset/>\n<feGaussianBlur stdDeviation=\"0.5\"/>\n<feComposite in2=\"hardAlpha\" operator=\"out\"/>\n<feColorMatrix type=\"matrix\" values=\"0 0 0 0 0.0335371 0 0 0 0 0.206463 0 0 0 0 0.183406 0 0 0 0.12 0\"/>\n<feBlend mode=\"normal\" in2=\"BackgroundImageFix\" result=\"effect1_dropShadow_4124_102997\"/>\n<feColorMatrix in=\"SourceAlpha\" type=\"matrix\" values=\"0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0\" result=\"hardAlpha\"/>\n<feOffset dy=\"1\"/>\n<feGaussianBlur stdDeviation=\"1.5\"/>\n<feComposite in2=\"hardAlpha\" operator=\"out\"/>\n<feColorMatrix type=\"matrix\" values=\"0 0 0 0 0.0335371 0 0 0 0 0.206463 0 0 0 0 0.183406 0 0 0 0.04 0\"/>\n<feBlend mode=\"normal\" in2=\"effect1_dropShadow_4124_102997\" result=\"effect2_dropShadow_4124_102997\"/>\n<feBlend mode=\"normal\" in=\"SourceGraphic\" in2=\"effect2_dropShadow_4124_102997\" result=\"shape\"/>\n</filter>\n<clipPath id=\"clip0_4124_102997\">\n<rect width=\"164\" height=\"164\" rx=\"82\" fill=\"white\"/>\n</clipPath>\n<clipPath id=\"clip1_4124_102997\">\n<rect x=\"16\" y=\"48\" width=\"132\" height=\"124\" rx=\"4\" fill=\"white\"/>\n</clipPath>\n<clipPath id=\"clip2_4124_102997\">\n<rect width=\"132\" height=\"132\" fill=\"white\" transform=\"translate(16 60)\"/>\n</clipPath>\n</defs>\n</svg>\n","<svg width=\"164\" height=\"164\" viewBox=\"0 0 164 164\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\">\n<g filter=\"url(#filter0_i_4124_103042)\">\n<g clip-path=\"url(#clip0_4124_103042)\">\n<rect width=\"164\" height=\"164\" rx=\"82\" fill=\"#F9FAFB\"/>\n<g filter=\"url(#filter1_dd_4124_103042)\">\n<g clip-path=\"url(#clip1_4124_103042)\">\n<rect x=\"16\" y=\"48\" width=\"132\" height=\"124\" rx=\"4\" fill=\"white\"/>\n<rect width=\"132\" height=\"12\" transform=\"translate(16 48)\" fill=\"#454D5F\"/>\n<circle opacity=\"0.24\" cx=\"23\" cy=\"54\" r=\"3\" fill=\"white\"/>\n<rect opacity=\"0.24\" x=\"30\" y=\"53\" width=\"10\" height=\"2\" rx=\"1\" fill=\"white\"/>\n<g clip-path=\"url(#clip2_4124_103042)\">\n<rect width=\"132\" height=\"132\" transform=\"translate(16 60)\" fill=\"white\"/>\n<rect opacity=\"0.16\" x=\"40\" y=\"160\" width=\"16\" height=\"2\" rx=\"1\" fill=\"#454D5F\"/>\n<rect opacity=\"0.24\" x=\"120\" y=\"158\" width=\"6\" height=\"6\" rx=\"1.5\" fill=\"#454D5F\"/>\n<rect opacity=\"0.24\" x=\"24\" y=\"157\" width=\"8\" height=\"8\" rx=\"4\" fill=\"#454D5F\"/>\n<path d=\"M54.1883 110.777L50.4383 109.859L51.9813 95.5625H67.3133V99.5469H55.8875L55.1063 106.52C55.549 106.259 56.1609 106.005 56.9422 105.758C57.7234 105.497 58.6154 105.367 59.618 105.367C60.9591 105.367 62.157 105.589 63.2117 106.031C64.2794 106.461 65.1844 107.092 65.9266 107.926C66.6688 108.746 67.2352 109.749 67.6258 110.934C68.0164 112.105 68.2117 113.427 68.2117 114.898C68.2117 116.214 68.0164 117.444 67.6258 118.59C67.2482 119.736 66.6753 120.745 65.907 121.617C65.1388 122.49 64.1688 123.173 62.9969 123.668C61.838 124.15 60.4643 124.391 58.8758 124.391C57.6909 124.391 56.5516 124.221 55.4578 123.883C54.3771 123.531 53.407 123.017 52.5477 122.34C51.6883 121.65 50.9982 120.803 50.4773 119.801C49.9565 118.785 49.657 117.62 49.5789 116.305H54.1883C54.3055 117.229 54.5594 118.017 54.95 118.668C55.3536 119.306 55.8875 119.794 56.5516 120.133C57.2156 120.471 57.9839 120.641 58.8563 120.641C59.6505 120.641 60.3341 120.504 60.907 120.23C61.4799 119.944 61.9552 119.54 62.3328 119.02C62.7234 118.486 63.0099 117.861 63.1922 117.145C63.3875 116.428 63.4852 115.634 63.4852 114.762C63.4852 113.928 63.3745 113.167 63.1531 112.477C62.9448 111.786 62.6258 111.188 62.1961 110.68C61.7794 110.172 61.2521 109.781 60.6141 109.508C59.976 109.221 59.2404 109.078 58.407 109.078C57.2872 109.078 56.4279 109.241 55.8289 109.566C55.243 109.892 54.6961 110.296 54.1883 110.777ZM91.3164 107.398V112.047C91.3164 114.273 91.0951 116.174 90.6523 117.75C90.2227 119.312 89.5977 120.582 88.7773 121.559C87.957 122.535 86.974 123.251 85.8281 123.707C84.6953 124.163 83.4258 124.391 82.0195 124.391C80.8997 124.391 79.8581 124.247 78.8945 123.961C77.944 123.674 77.0846 123.225 76.3164 122.613C75.5482 122.001 74.8906 121.214 74.3438 120.25C73.8099 119.273 73.3932 118.108 73.0938 116.754C72.8073 115.4 72.6641 113.831 72.6641 112.047V107.398C72.6641 105.159 72.8854 103.271 73.3281 101.734C73.7708 100.185 74.4023 98.9284 75.2227 97.9648C76.043 96.9883 77.0195 96.2786 78.1523 95.8359C79.2982 95.3932 80.5742 95.1719 81.9805 95.1719C83.1133 95.1719 84.1549 95.3151 85.1055 95.6016C86.069 95.875 86.9284 96.3112 87.6836 96.9102C88.4518 97.5091 89.1029 98.2904 89.6367 99.2539C90.1836 100.204 90.6003 101.357 90.8867 102.711C91.1732 104.052 91.3164 105.615 91.3164 107.398ZM86.6094 112.711V106.695C86.6094 105.562 86.5443 104.566 86.4141 103.707C86.2839 102.835 86.0885 102.099 85.8281 101.5C85.5807 100.888 85.2682 100.393 84.8906 100.016C84.513 99.625 84.0833 99.3451 83.6016 99.1758C83.1198 98.9935 82.5794 98.9023 81.9805 98.9023C81.2513 98.9023 80.6003 99.0456 80.0273 99.332C79.4544 99.6055 78.9727 100.048 78.582 100.66C78.1914 101.272 77.8919 102.079 77.6836 103.082C77.4883 104.072 77.3906 105.276 77.3906 106.695V112.711C77.3906 113.857 77.4557 114.866 77.5859 115.738C77.7161 116.611 77.9115 117.359 78.1719 117.984C78.4323 118.596 78.7448 119.104 79.1094 119.508C79.487 119.898 79.9167 120.185 80.3984 120.367C80.8932 120.549 81.4336 120.641 82.0195 120.641C82.7617 120.641 83.4193 120.497 83.9922 120.211C84.5651 119.924 85.0469 119.469 85.4375 118.844C85.8281 118.206 86.1211 117.379 86.3164 116.363C86.5117 115.348 86.6094 114.13 86.6094 112.711ZM114.851 107.398V112.047C114.851 114.273 114.629 116.174 114.187 117.75C113.757 119.312 113.132 120.582 112.312 121.559C111.491 122.535 110.508 123.251 109.362 123.707C108.23 124.163 106.96 124.391 105.554 124.391C104.434 124.391 103.392 124.247 102.429 123.961C101.478 123.674 100.619 123.225 99.8508 122.613C99.0826 122.001 98.425 121.214 97.8781 120.25C97.3443 119.273 96.9276 118.108 96.6281 116.754C96.3417 115.4 96.1984 113.831 96.1984 112.047V107.398C96.1984 105.159 96.4198 103.271 96.8625 101.734C97.3052 100.185 97.9367 98.9284 98.757 97.9648C99.5773 96.9883 100.554 96.2786 101.687 95.8359C102.833 95.3932 104.109 95.1719 105.515 95.1719C106.648 95.1719 107.689 95.3151 108.64 95.6016C109.603 95.875 110.463 96.3112 111.218 96.9102C111.986 97.5091 112.637 98.2904 113.171 99.2539C113.718 100.204 114.135 101.357 114.421 102.711C114.708 104.052 114.851 105.615 114.851 107.398ZM110.144 112.711V106.695C110.144 105.562 110.079 104.566 109.948 103.707C109.818 102.835 109.623 102.099 109.362 101.5C109.115 100.888 108.803 100.393 108.425 100.016C108.047 99.625 107.618 99.3451 107.136 99.1758C106.654 98.9935 106.114 98.9023 105.515 98.9023C104.786 98.9023 104.135 99.0456 103.562 99.332C102.989 99.6055 102.507 100.048 102.116 100.66C101.726 101.272 101.426 102.079 101.218 103.082C101.023 104.072 100.925 105.276 100.925 106.695V112.711C100.925 113.857 100.99 114.866 101.12 115.738C101.251 116.611 101.446 117.359 101.706 117.984C101.967 118.596 102.279 119.104 102.644 119.508C103.021 119.898 103.451 120.185 103.933 120.367C104.428 120.549 104.968 120.641 105.554 120.641C106.296 120.641 106.954 120.497 107.527 120.211C108.099 119.924 108.581 119.469 108.972 118.844C109.362 118.206 109.655 117.379 109.851 116.363C110.046 115.348 110.144 114.13 110.144 112.711Z\" fill=\"#C6CAD2\"/>\n</g>\n</g>\n</g>\n</g>\n</g>\n<defs>\n<filter id=\"filter0_i_4124_103042\" x=\"0\" y=\"-1\" width=\"164\" height=\"165\" filterUnits=\"userSpaceOnUse\" color-interpolation-filters=\"sRGB\">\n<feFlood flood-opacity=\"0\" result=\"BackgroundImageFix\"/>\n<feBlend mode=\"normal\" in=\"SourceGraphic\" in2=\"BackgroundImageFix\" result=\"shape\"/>\n<feColorMatrix in=\"SourceAlpha\" type=\"matrix\" values=\"0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0\" result=\"hardAlpha\"/>\n<feOffset dy=\"-1\"/>\n<feGaussianBlur stdDeviation=\"1.5\"/>\n<feComposite in2=\"hardAlpha\" operator=\"arithmetic\" k2=\"-1\" k3=\"1\"/>\n<feColorMatrix type=\"matrix\" values=\"0 0 0 0 0.1056 0 0 0 0 0.11904 0 0 0 0 0.1344 0 0 0 0.2 0\"/>\n<feBlend mode=\"normal\" in2=\"shape\" result=\"effect1_innerShadow_4124_103042\"/>\n</filter>\n<filter id=\"filter1_dd_4124_103042\" x=\"13\" y=\"46\" width=\"138\" height=\"130\" filterUnits=\"userSpaceOnUse\" color-interpolation-filters=\"sRGB\">\n<feFlood flood-opacity=\"0\" result=\"BackgroundImageFix\"/>\n<feColorMatrix in=\"SourceAlpha\" type=\"matrix\" values=\"0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0\" result=\"hardAlpha\"/>\n<feOffset/>\n<feGaussianBlur stdDeviation=\"0.5\"/>\n<feComposite in2=\"hardAlpha\" operator=\"out\"/>\n<feColorMatrix type=\"matrix\" values=\"0 0 0 0 0.0335371 0 0 0 0 0.206463 0 0 0 0 0.183406 0 0 0 0.12 0\"/>\n<feBlend mode=\"normal\" in2=\"BackgroundImageFix\" result=\"effect1_dropShadow_4124_103042\"/>\n<feColorMatrix in=\"SourceAlpha\" type=\"matrix\" values=\"0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0\" result=\"hardAlpha\"/>\n<feOffset dy=\"1\"/>\n<feGaussianBlur stdDeviation=\"1.5\"/>\n<feComposite in2=\"hardAlpha\" operator=\"out\"/>\n<feColorMatrix type=\"matrix\" values=\"0 0 0 0 0.0335371 0 0 0 0 0.206463 0 0 0 0 0.183406 0 0 0 0.04 0\"/>\n<feBlend mode=\"normal\" in2=\"effect1_dropShadow_4124_103042\" result=\"effect2_dropShadow_4124_103042\"/>\n<feBlend mode=\"normal\" in=\"SourceGraphic\" in2=\"effect2_dropShadow_4124_103042\" result=\"shape\"/>\n</filter>\n<clipPath id=\"clip0_4124_103042\">\n<rect width=\"164\" height=\"164\" rx=\"82\" fill=\"white\"/>\n</clipPath>\n<clipPath id=\"clip1_4124_103042\">\n<rect x=\"16\" y=\"48\" width=\"132\" height=\"124\" rx=\"4\" fill=\"white\"/>\n</clipPath>\n<clipPath id=\"clip2_4124_103042\">\n<rect width=\"132\" height=\"132\" fill=\"white\" transform=\"translate(16 60)\"/>\n</clipPath>\n</defs>\n</svg>\n","<svg width=\"164\" height=\"164\" viewBox=\"0 0 164 164\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\">\n<g filter=\"url(#filter0_i_7107_90986)\">\n<g clip-path=\"url(#clip0_7107_90986)\">\n<rect width=\"164\" height=\"164\" rx=\"82\" fill=\"#F9FAFB\"/>\n<g filter=\"url(#filter1_dd_7107_90986)\">\n<rect x=\"38.588\" y=\"31.1113\" width=\"256\" height=\"140\" rx=\"6\" transform=\"rotate(5 38.588 31.1113)\" fill=\"white\" shape-rendering=\"crispEdges\"/>\n<rect x=\"49.6952\" y=\"53.4668\" width=\"104\" height=\"36\" rx=\"4\" transform=\"rotate(8 49.6952 53.4668)\" fill=\"#F3F4F6\"/>\n<rect width=\"230\" height=\"12\" transform=\"translate(-1.77661 60.6738) rotate(-10)\" fill=\"#454D5F\"/>\n<circle opacity=\"0.24\" cx=\"6.15896\" cy=\"65.3671\" r=\"3\" transform=\"rotate(-10 6.15896 65.3671)\" fill=\"white\"/>\n<rect opacity=\"0.24\" x=\"12.8789\" y=\"63.166\" width=\"10\" height=\"2\" rx=\"1\" transform=\"rotate(-10 12.8789 63.166)\" fill=\"white\"/>\n<rect x=\"43.9305\" y=\"100.689\" width=\"48\" height=\"36\" rx=\"4\" transform=\"rotate(3 43.9305 100.689)\" fill=\"#F3F4F6\"/>\n<rect x=\"41.8835\" y=\"146.205\" width=\"48\" height=\"36\" rx=\"4\" transform=\"rotate(9 41.8835 146.205)\" fill=\"#F3F4F6\"/>\n<rect x=\"101.884\" y=\"106.895\" width=\"48\" height=\"36\" rx=\"4\" transform=\"rotate(10 101.884 106.895)\" fill=\"#F3F4F6\"/>\n<rect x=\"96.3936\" y=\"150.604\" width=\"48\" height=\"36\" rx=\"4\" transform=\"rotate(5 96.3936 150.604)\" fill=\"#F3F4F6\"/>\n</g>\n</g>\n</g>\n<defs>\n<filter id=\"filter0_i_7107_90986\" x=\"0\" y=\"-1\" width=\"164\" height=\"165\" filterUnits=\"userSpaceOnUse\" color-interpolation-filters=\"sRGB\">\n<feFlood flood-opacity=\"0\" result=\"BackgroundImageFix\"/>\n<feBlend mode=\"normal\" in=\"SourceGraphic\" in2=\"BackgroundImageFix\" result=\"shape\"/>\n<feColorMatrix in=\"SourceAlpha\" type=\"matrix\" values=\"0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0\" result=\"hardAlpha\"/>\n<feOffset dy=\"-1\"/>\n<feGaussianBlur stdDeviation=\"1.5\"/>\n<feComposite in2=\"hardAlpha\" operator=\"arithmetic\" k2=\"-1\" k3=\"1\"/>\n<feColorMatrix type=\"matrix\" values=\"0 0 0 0 0.1056 0 0 0 0 0.11904 0 0 0 0 0.1344 0 0 0 0.2 0\"/>\n<feBlend mode=\"normal\" in2=\"shape\" result=\"effect1_innerShadow_7107_90986\"/>\n</filter>\n<filter id=\"filter1_dd_7107_90986\" x=\"-4.77661\" y=\"18.7344\" width=\"301.391\" height=\"178.156\" filterUnits=\"userSpaceOnUse\" color-interpolation-filters=\"sRGB\">\n<feFlood flood-opacity=\"0\" result=\"BackgroundImageFix\"/>\n<feColorMatrix in=\"SourceAlpha\" type=\"matrix\" values=\"0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0\" result=\"hardAlpha\"/>\n<feOffset/>\n<feGaussianBlur stdDeviation=\"1\"/>\n<feComposite in2=\"hardAlpha\" operator=\"out\"/>\n<feColorMatrix type=\"matrix\" values=\"0 0 0 0 0.0775545 0 0 0 0 0.0335371 0 0 0 0 0.206463 0 0 0 0.12 0\"/>\n<feBlend mode=\"normal\" in2=\"BackgroundImageFix\" result=\"effect1_dropShadow_7107_90986\"/>\n<feColorMatrix in=\"SourceAlpha\" type=\"matrix\" values=\"0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0\" result=\"hardAlpha\"/>\n<feOffset dy=\"1\"/>\n<feGaussianBlur stdDeviation=\"1.5\"/>\n<feComposite in2=\"hardAlpha\" operator=\"out\"/>\n<feColorMatrix type=\"matrix\" values=\"0 0 0 0 0.0775545 0 0 0 0 0.0335371 0 0 0 0 0.206463 0 0 0 0.04 0\"/>\n<feBlend mode=\"normal\" in2=\"effect1_dropShadow_7107_90986\" result=\"effect2_dropShadow_7107_90986\"/>\n<feBlend mode=\"normal\" in=\"SourceGraphic\" in2=\"effect2_dropShadow_7107_90986\" result=\"shape\"/>\n</filter>\n<clipPath id=\"clip0_7107_90986\">\n<rect width=\"164\" height=\"164\" rx=\"82\" fill=\"white\"/>\n</clipPath>\n</defs>\n</svg>\n","<svg width=\"164\" height=\"164\" viewBox=\"0 0 164 164\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\">\n<g filter=\"url(#filter0_i_7083_91308)\">\n<g clip-path=\"url(#clip0_7083_91308)\">\n<rect width=\"164\" height=\"164\" rx=\"82\" fill=\"#F9FAFB\"/>\n<g filter=\"url(#filter1_dd_7083_91308)\">\n<rect x=\"16\" y=\"48\" width=\"132\" height=\"128\" rx=\"4\" fill=\"white\"/>\n<circle cx=\"82\" cy=\"72\" r=\"12\" fill=\"#E8EAED\"/>\n<rect x=\"67\" y=\"92\" width=\"30\" height=\"6\" rx=\"3\" fill=\"#E8EAED\"/>\n<rect x=\"31\" y=\"114.002\" width=\"102\" height=\"16\" rx=\"4\" fill=\"#E8EAED\"/>\n<rect x=\"31\" y=\"142.002\" width=\"102\" height=\"16\" rx=\"4\" fill=\"#E8EAED\"/>\n</g>\n</g>\n</g>\n<defs>\n<filter id=\"filter0_i_7083_91308\" x=\"0\" y=\"-1\" width=\"164\" height=\"165\" filterUnits=\"userSpaceOnUse\" color-interpolation-filters=\"sRGB\">\n<feFlood flood-opacity=\"0\" result=\"BackgroundImageFix\"/>\n<feBlend mode=\"normal\" in=\"SourceGraphic\" in2=\"BackgroundImageFix\" result=\"shape\"/>\n<feColorMatrix in=\"SourceAlpha\" type=\"matrix\" values=\"0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0\" result=\"hardAlpha\"/>\n<feOffset dy=\"-1\"/>\n<feGaussianBlur stdDeviation=\"1.5\"/>\n<feComposite in2=\"hardAlpha\" operator=\"arithmetic\" k2=\"-1\" k3=\"1\"/>\n<feColorMatrix type=\"matrix\" values=\"0 0 0 0 0.1056 0 0 0 0 0.11904 0 0 0 0 0.1344 0 0 0 0.2 0\"/>\n<feBlend mode=\"normal\" in2=\"shape\" result=\"effect1_innerShadow_7083_91308\"/>\n</filter>\n<filter id=\"filter1_dd_7083_91308\" x=\"13\" y=\"46\" width=\"138\" height=\"134\" filterUnits=\"userSpaceOnUse\" color-interpolation-filters=\"sRGB\">\n<feFlood flood-opacity=\"0\" result=\"BackgroundImageFix\"/>\n<feColorMatrix in=\"SourceAlpha\" type=\"matrix\" values=\"0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0\" result=\"hardAlpha\"/>\n<feOffset/>\n<feGaussianBlur stdDeviation=\"0.5\"/>\n<feComposite in2=\"hardAlpha\" operator=\"out\"/>\n<feColorMatrix type=\"matrix\" values=\"0 0 0 0 0.0335371 0 0 0 0 0.206463 0 0 0 0 0.183406 0 0 0 0.12 0\"/>\n<feBlend mode=\"normal\" in2=\"BackgroundImageFix\" result=\"effect1_dropShadow_7083_91308\"/>\n<feColorMatrix in=\"SourceAlpha\" type=\"matrix\" values=\"0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0\" result=\"hardAlpha\"/>\n<feOffset dy=\"1\"/>\n<feGaussianBlur stdDeviation=\"1.5\"/>\n<feComposite in2=\"hardAlpha\" operator=\"out\"/>\n<feColorMatrix type=\"matrix\" values=\"0 0 0 0 0.0335371 0 0 0 0 0.206463 0 0 0 0 0.183406 0 0 0 0.04 0\"/>\n<feBlend mode=\"normal\" in2=\"effect1_dropShadow_7083_91308\" result=\"effect2_dropShadow_7083_91308\"/>\n<feBlend mode=\"normal\" in=\"SourceGraphic\" in2=\"effect2_dropShadow_7083_91308\" result=\"shape\"/>\n</filter>\n<clipPath id=\"clip0_7083_91308\">\n<rect width=\"164\" height=\"164\" rx=\"82\" fill=\"white\"/>\n</clipPath>\n</defs>\n</svg>\n","import React from \"react\";\nimport styled from \"styled-components\";\nimport ForbiddenErrorImage from \"../assets/images/errors/403-image.svg\";\nimport AppNotFoundImage from \"../assets/images/errors/404-image.svg\";\nimport ServerError500Image from \"../assets/images/errors/500-image.svg\";\nimport GeneralErrorImage from \"../assets/images/errors/general-error.svg\";\nimport LoginErrorImage from \"../assets/images/errors/login-error.svg\";\nimport { colors } from \"../styling/colors.js\";\nimport { API_STATUS_CODES } from \"./constants.js\";\n\nconst HOME_URL = \"/home\";\n\nconst VerticalWrapper = styled.div`\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n height: 100%;\n`;\n\ninterface Props {\n title: string;\n errorMessage?: string | React.ReactNode;\n buttonText?: string;\n handleButtonClick?: () => void;\n errorCode?: API_STATUS_CODES | \"LOGIN_FAILURE\";\n buttonPath?: string;\n image?: string; // when not set, the image will be based on the errorCode\n secondaryButtonText?: string;\n secondaryButtonAction?: () => void;\n hideActions?: boolean;\n mainButtonType?: \"primary\" | \"ghost\";\n // showActionsOnEmbedRoute?: boolean; // by default, actions are hidden on embed pages\n}\n\n// Most of the errors have this styling anyway\nconst ErrorWrapper = styled.div`\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n height: calc(100vh);\n text-align: center;\n .bold-text {\n font-weight: 500;\n font-size: 24px;\n }\n .page-unavailable-img {\n width: 35%;\n }\n .button-position {\n margin: auto;\n }\n`;\n\nconst TextWrapper = styled.div`\n margin-top: 30px;\n margin-bottom: 30px;\n max-width: 500px;\n`;\n\nconst Title = styled.h3`\n font-size: 1.25rem;\n font-weight: 500;\n margin-bottom: 0.5rem;\n`;\n\nconst ErrorMessage = styled.p`\n color: ${colors.GREY_500};\n`;\n\nconst Button = styled.button`\n border: 1px solid ${colors.GREY_100};\n color: ${colors.GREY_600};\n border-radius: 6px;\n padding: 2px 6px;\n font-size: 1rem;\n font-weight: 400;\n cursor: pointer;\n\n &:hover {\n background-color: ${colors.GREY_100};\n }\n`;\n\nconst ErrorComponent = ({\n title,\n errorMessage,\n buttonText,\n handleButtonClick,\n errorCode,\n buttonPath,\n image: overrideImage,\n secondaryButtonAction,\n secondaryButtonText,\n hideActions,\n}: Props) => {\n let ImageComponent = overrideImage ?? GeneralErrorImage;\n if (!overrideImage) {\n switch (errorCode) {\n case API_STATUS_CODES.RESOURCE_NOT_FOUND:\n ImageComponent = AppNotFoundImage;\n break;\n case API_STATUS_CODES.SERVER_ERROR:\n ImageComponent = ServerError500Image;\n break;\n case API_STATUS_CODES.RESOURCE_FORBIDDEN:\n ImageComponent = ForbiddenErrorImage;\n break;\n case API_STATUS_CODES.TIMEOUT:\n ImageComponent = GeneralErrorImage;\n break;\n case \"LOGIN_FAILURE\":\n ImageComponent = LoginErrorImage;\n break;\n default:\n ImageComponent = GeneralErrorImage; //we should have covered all the cases and Koala should not show, keeping it here since we do not have a default one\n }\n }\n const showActions = !hideActions;\n\n return (\n <ErrorWrapper data-test=\"app-error-container\" className=\"error-wrapper\">\n <VerticalWrapper>\n <ImageComponent />\n <TextWrapper>\n <Title>{title}</Title>\n {errorMessage && (\n <ErrorMessage data-test=\"error-page-subtext\">\n {errorMessage}\n </ErrorMessage>\n )}\n </TextWrapper>\n {showActions && (\n <div style={{ display: \"flex\", alignItems: \"center\", gap: \"12px\" }}>\n {secondaryButtonText && secondaryButtonAction && (\n <Button type=\"button\" onClick={secondaryButtonAction}>\n {secondaryButtonText}\n </Button>\n )}\n <Button\n type={\"button\"}\n onClick={() =>\n handleButtonClick\n ? handleButtonClick()\n : (window.location.pathname = buttonPath ?? HOME_URL)\n }\n data-test=\"error-component-button\"\n >\n {buttonText ? buttonText : \"Return Home\"}\n </Button>\n </div>\n )}\n </VerticalWrapper>\n </ErrorWrapper>\n );\n};\n\nexport default ErrorComponent;\n","import React from \"react\";\nimport styled from \"styled-components\";\nimport { API_STATUS_CODES } from \"./constants.js\";\nimport ErrorComponent from \"./error-component.jsx\";\n\nconst Wrapper = styled.div`\n text-align: center;\n .bold-text {\n font-weight: 500;\n font-size: 24px;\n }\n .page-unavailable-img {\n width: 35%;\n }\n .button-position {\n margin: auto;\n }\n height: 100%;\n`;\n\nexport const PageNotFound = ({\n title = \"Content not found\",\n errorMessage = \"We couldn’t find the page you were looking for. Make sure that you have the right URL. \",\n buttonPath,\n buttonText,\n onButtonClick,\n hideActions,\n}: {\n title?: string;\n errorMessage?: string | React.ReactElement;\n buttonPath?: string;\n buttonText?: string;\n onButtonClick?: () => void;\n hideActions?: boolean;\n}) => {\n return (\n <Wrapper>\n <ErrorComponent\n errorCode={API_STATUS_CODES.RESOURCE_NOT_FOUND}\n title={title}\n errorMessage={errorMessage}\n hideActions={hideActions}\n buttonPath={buttonPath}\n buttonText={buttonText}\n mainButtonType={\"ghost\"}\n handleButtonClick={onButtonClick}\n />\n </Wrapper>\n );\n};\n","import { useEffect } from \"react\";\nimport { useRouteError } from \"react-router\";\nimport { editorBridge } from \"../../../edit-mode/superblocks-editor-bridge.js\";\nimport { isEditMode } from \"../is-edit-mode.js\";\nimport {\n ErrorIconContainer,\n ErrorTitle,\n ErrorMessage,\n ErrorStack,\n ErrorDetails,\n StyledClarkIcon,\n ErrorContainer,\n ErrorContent,\n ErrorSummary,\n SecondaryButton,\n ActionsContainer,\n} from \"./common.js\";\nimport { FixWithClarkButton } from \"./fix-with-clark-button.jsx\";\n\nexport function RouteLoadError() {\n const error = useRouteError() as Error;\n\n // we do this dynamically because this component will probably be loaded\n // before the app has even bootstrapped, because we have an error during route loading\n // (i.e. syntax error, missing import, etc.)\n useEffect(() => {\n const link = document.createElement(\"link\");\n link.href =\n \"https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap\";\n link.rel = \"stylesheet\";\n document.head.appendChild(link);\n // send a message to the ui to remove the loading state\n editorBridge.sendReady();\n if (isEditMode()) {\n editorBridge.sendLoadError(String(error));\n }\n\n return () => {\n document.head.removeChild(link);\n };\n }, [error]);\n\n console.error(\"Route load error\", error);\n return (\n <ErrorContainer>\n <ErrorContent>\n <ErrorIconContainer>\n <StyledClarkIcon />\n </ErrorIconContainer>\n\n <ErrorTitle>Something went wrong</ErrorTitle>\n <ErrorMessage>{error?.message || \"Unknown error\"}</ErrorMessage>\n\n <ActionsContainer>\n {isEditMode() && <FixWithClarkButton error={error} />}\n <SecondaryButton\n onClick={() => {\n window.location.reload();\n }}\n >\n Refresh page\n </SecondaryButton>\n </ActionsContainer>\n\n {error && (\n <ErrorDetails>\n <ErrorSummary>Full details</ErrorSummary>\n <ErrorStack>{error.stack}</ErrorStack>\n </ErrorDetails>\n )}\n </ErrorContent>\n </ErrorContainer>\n );\n}\n","import \"../edit-mode/edit-style.css\";\n\n// CRITICAL: Early console patching before any other JS imports\nimport LibraryEarlyConsoleBuffer from \"./tracing/early-console-buffer.js\";\nLibraryEarlyConsoleBuffer.getInstance().patchEarly();\n\n// Register all standard HTML elements with default properties panels\nimport { registerHtmlElements } from \"./user-facing/components/html/register-html-elements.js\";\nregisterHtmlElements();\n\nimport type { CreateChild } from \"@superblocksteam/library-shared/types\";\nexport { type CreateChild };\n\n// Superblocks Global Context\nexport { default as SuperblocksProvider } from \"./user-facing/sb-provider.js\";\nexport {\n useSuperblocksGroups,\n useSuperblocksUser,\n useSuperblocksProfiles,\n getAppMode,\n} from \"./internal-details/superblocks-context.js\";\n\n// User-facing components\nexport { App } from \"./user-facing/components/app/index.jsx\";\nexport {\n registerComponent,\n type PropertiesPanelDefinition,\n} from \"./user-facing/components/custom/register-custom-component.js\";\nexport { PageNotFound } from \"./user-facing/error-pages/page-not-found.jsx\";\nexport { RouteLoadError } from \"./internal-details/internal-components/route-load-error.jsx\";\n\nexport { useApiStateful as useApi } from \"./internal-details/use-api.js\";\n\n// User-facing types\nexport {\n Prop,\n Section,\n PropsCategory,\n} from \"./user-facing/properties-panel/props-builder.js\";\nexport { tailwindStylesCategory } from \"./user-facing/properties-panel/mixins/styles-category.js\";\n\n// TODO: Cleanup (remove Dim inside Property)\nexport { Property } from \"@superblocksteam/library-shared\";\nexport type { EditorConfig } from \"@superblocksteam/library-shared\";\nexport type {\n EditorTemplate,\n CreationContext,\n} from \"./internal-details/sb-wrapper.jsx\";\n\n// TODO: Move these to the library-shared package\nexport type {\n FromChildToParentMessageTypes,\n FromChildToParentMessageTypesMap,\n FromParentToChildMessageTypes,\n FromParentToChildMessageTypesMap,\n} from \"./internal-details/lib/types.js\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuFA,MAAa,6BACX,aACA,2BACuC;CACvC,MAAM,OACJ,OAAOA,gBAAc,WACjBA,cACAA,YAAU,eAAeA,YAAU;AAEzC,KAAI,CAAC,KACH,OAAM,IAAI,MACR,iFAAiFA,cAClF;CAGH,MAAM,eAAe,uBAAuBC,uBAAqB;CAGjE,MAAM,cAAc,CAAC,CAAC,aAAa,MAChC,MAAM,EAAE,SAAS,cAAc,EAAE,aAAc,MACjD;AAED,oBAAU,yBAAyB;AACjC,gBAAc,CAAC,uBAAuB,wBACpC,MACAA,uBACD;GACD;AAEF,oBAAU,kBAAkB,aAC1B,MACAD,aACAC,uBACD;AACD,oBAAU,kBAAkB,gBAAgB,MAAM,gBAAgB,EAAE,CAAC;CAErE,MAAMC,sBAAoC,EAAE;AAG5C,KAAI,aAAa;AACf,sBAAoB,cAAc;AAClC,qBAAU,kBAAkB,gBAAgB,MAAM,oBAAoB;;CAIxE,MAAMC,qBAAyD;EAC7D,oBACE,mBACuC;GACvC,MAAMC,UAAmB,eAAe,WAAW;IACjD,aAAa;IACb,UAAU;IACX;AACD,sBAAU,kBAAkB,kBAAkB,MAAM;IAClD,GAAG;IACH;IACD,CAAC;AACF,UAAO;;EAET,eACE,WACuC;AACvC,sBAAU,kBAAkB,gBAAgB,MAAM;IAChD,GAAG;IACH,GAAG;IACJ,CAAC;AACF,UAAO;;EAEV;AAED,QAAO;;;;;;;;;;;;ACpJT,MAAa,wBACX,UAAyE,EAAE,KAC/B;CAC5C,MAAM,YAAY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ACE,oBACI,mBAAmB,GAClB,OAAO,SAAS,WAAW,cAAc;KAEhD,aAAU;eAET,aAAa,aAAa;MACpB;KACL;MAEQ;GACL;;AAInB,8BAAe;;;;ACzJf,MAAM,UAAU,OAAO,GAAG;;;;;;;;;;;;;;AAe1B,MAAa,gBAAgB,EAC3B,QAAQ,qBACR,eAAe,2FACf,YACA,YACA,eACA,kBAQI;AACJ,QACE,oBAAC,qBACC,oBAACO;EACC,WAAW,iBAAiB;EACrB;EACO;EACD;EACD;EACA;EACZ,gBAAgB;EAChB,mBAAmB;GACnB,GACM;;;;;AC5Bd,SAAgB,iBAAiB;CAC/B,MAAM,QAAQ,eAAe;AAK7B,iBAAgB;EACd,MAAM,OAAO,SAAS,cAAc,OAAO;AAC3C,OAAK,OACH;AACF,OAAK,MAAM;AACX,WAAS,KAAK,YAAY,KAAK;AAE/B,eAAa,WAAW;AACxB,MAAI,YAAY,CACd,cAAa,cAAc,OAAO,MAAM,CAAC;AAG3C,eAAa;AACX,YAAS,KAAK,YAAY,KAAK;;IAEhC,CAAC,MAAM,CAAC;AAEX,SAAQ,MAAM,oBAAoB,MAAM;AACxC,QACE,oBAAC,4BACC,qBAAC;EACC,oBAAC,gCACC,oBAAC,oBAAkB,GACA;EAErB,oBAAC,wBAAW,yBAAiC;EAC7C,oBAAC,0BAAc,OAAO,WAAW,kBAA+B;EAEhE,qBAAC,+BACE,YAAY,IAAI,oBAAC,sBAA0B,QAAS,EACrD,oBAAC;GACC,eAAe;AACb,WAAO,SAAS,QAAQ;;aAE3B;IAEiB,IACD;EAElB,SACC,qBAAC,2BACC,oBAAC,0BAAa,iBAA2B,EACzC,oBAAC,wBAAY,MAAM,QAAmB,IACzB;KAEJ,GACA;;;;;ACnErBC,6BAA0B,aAAa,CAAC,YAAY;AAIpD,sBAAsB"}
1
+ {"version":3,"file":"index.js","names":["Component","propertiesDefinition","defaultEditorConfig: EditorConfig","chainableComponent: Chainable<React.ComponentProps<T>>","catalog: Catalog","cachedRootFontSize: number | undefined","variables: ExtractedVariables","cachedSizePresets: {\n height: ThemeToken[];\n width: ThemeToken[];\n spacing: ThemeToken[];\n} | null","sizePresets: ThemeToken[]","cachedBorderPresets: {\n borderWidth: ThemeToken[];\n borderRadius: ThemeToken[];\n boxShadow: ThemeToken[];\n} | null","sizePresets: ThemeToken[]","boxShadowPresets: ThemeToken[]","cachedColorPresets: ThemeToken[] | null","propertiesDefinition","TYPOGRAPHY_PRIORITIZED_PROPERTIES: TailwindPropertyKey[]","CONTAINER_PRIORITIZED_PROPERTIES: TailwindPropertyKey[]","sections: PropertiesPanelDefinition<React.ComponentProps<any>>","handleBootstrapResponse: IframeEventHandler<\n \"sb-bootstrap-response\"\n>","rootStore","rootStore","BuildErrorNotification","buildError: BuildError","rootStore","properties: Record<string, PropertyInfo>","rootStore","context: CreationContext","context","editorTemplateCreateRequest","baseProperties","otherComponentsUpdates","runtimeTrackingStore: RuntimeTrackingStore","serverUrl: string","timeoutId: ReturnType<typeof setTimeout> | undefined","stopSocketHeartbeat: (() => void) | undefined","action","payload: ReparentRequest","payload: DeleteRequest","operation","asSetProperties: SetPropertiesRequest","payload: SetPropertiesRequest","SourceUpdateApi","editStore: EditStore","componentsManager: ComponentRegistry","propertiesDefinition","editStore: EditStore | undefined","sourceNode: SourceCodeNode","current: SbSelector | undefined","registeredMatches: SbSelector[]","root: RootStore","properties: Record<string, PropertyInfo<unknown>>","Property","root: RootStore","editStore: EditStore","selectorId","component: RuntimeComponentData","path: PathNode[]","current: SbSelector | undefined","children: SubtreeNode[]","editStore: EditStore","out: Record<SbElement, RuntimeSyncComposite | null>","UIStore","OperationManager","PropertiesPanelManager","RuntimeTrackingStore","ConnectionManager","rootStore","useHotkeysOriginal","NamePill: ReturnType<typeof observer<NamePillProps>>","NamePill","transforms: Array<{ computed: string; element: HTMLElement }>","current: HTMLElement | null","data: TransformData","data","values","width","height","components: { selectorId: SbSelector; sourceId: SbElement }[]","selectedRects: SelectionInfo[]","handleCaptureScreenshot: IframeEventHandler<\n \"capture-screenshot\"\n >","_setReloadKey: (fn: (currentKey: number) => number) => void","handleInit: IframeEventHandler<\"sb-init\">","sourceUpdateApi","handleTokenUpdate: IframeEventHandler<\"sb-update-token\">","IframeConnected","handleDragStart: IframeEventHandler<\"dragstart\">","pendingLogs: Array<{\n level: \"log\" | \"warn\" | \"error\" | \"info\" | \"debug\";\n args: any[];\n stack?: string;\n }>","flushTimer: NodeJS.Timeout | null","stack: string | undefined","rootStore","WithUserWrapper","timeout: NodeJS.Timeout","bootstrapResponseListener: IframeEventHandler<\n \"sb-bootstrap-response\"\n >","updateActiveAgentsListener: IframeEventHandler<\n \"sb-update-active-agents\"\n >","retrievePropertyPanelPropsListener: IframeEventHandler<\n \"sb-retrieve-property-panel-props\"\n >","editOperationAcknowledgeListener: IframeEventHandler<\n \"sb-edit-operation-acknowledge\"\n >","updatePropertyWithEffectsListener: IframeEventHandler<\n \"sb-update-property-with-effects\"\n >","createComponentListener: IframeEventHandler<\n \"sb-create-component\"\n >","error","setInteractionModeListener: IframeEventHandler<\n \"set-interaction-mode\"\n >","globalSyncListener: IframeEventHandler<\"sb-global-sync\">","navigateToListener: IframeEventHandler<\"route-change\">","aiUpdatesListener: IframeEventHandler<\"ai-updates\">","hmrReloadListener: IframeEventHandler<\"hmr-reload-request\">","action","sourceIds: SbElement[]","throttle","timeoutId: ReturnType<typeof setTimeout>","modifiedElements: Array<{\n element: HTMLElement;\n hadInlineStyle: boolean;\n originalValue: string;\n }>","hoveredPills: { selectorId: SbSelector; noSelect?: boolean }[]","hoveredActual: { selectorId: SbSelector; noSelect?: boolean }[]","actualSelectorId: SbSelector | undefined","rootStore","current: HTMLElement | null","throttle","observer","rootStore","Auth0Wrapper","EmbedWrapper","timeout: NodeJS.Timeout","rootStore","bootstrapResponseListener: IframeEventHandler<\n \"sb-bootstrap-response\"\n >","globalSyncListener: IframeEventHandler<\"sb-global-sync\">","navigateToListener: IframeEventHandler<\"route-change\">","action","rootStore","rootStore","VARIABLES: Record<string, string>","VARIABLE_VALUES: Record<keyof typeof VARIABLES, string>","componentVariables: Record<string, string>","componentVariableValues: Record<string, string>","registry: Record<string, string>","loadApisIntoLibrary","Auth0Wrapper","EditorAuth0Wrapper","AppAuth0Wrapper","EmbedWrapper","EditorEmbedWrapper","AppEmbedWrapper","SbProvider","resolvePromiseListener: IframeEventHandler<\"resolve-promise\">","rejectPromiseListener: IframeEventHandler<\"reject-promise\">","context","InteractionLayer","editorConfig: EditorConfig","SuperblocksProvider","context","ErrorMessage","colors","GeneralErrorImage","AppNotFoundImage","ServerError500Image","ForbiddenErrorImage","LoginErrorImage","ErrorComponent","LibraryEarlyConsoleBuffer"],"sources":["../../src/lib/internal-details/sb-wrapper.tsx","../../src/lib/user-facing/properties-panel/mixins/inline-styles-category.ts","../../src/lib/user-facing/properties-panel/mixins/convert-rem-to-pixels.ts","../../src/lib/user-facing/properties-panel/mixins/extract-variables.ts","../../src/lib/user-facing/properties-panel/mixins/style-tokens-size.ts","../../src/lib/user-facing/properties-panel/mixins/style-tokens-border.ts","../../src/lib/user-facing/properties-panel/mixins/style-tokens-color.ts","../../src/lib/user-facing/properties-panel/mixins/styles-category.ts","../../src/lib/user-facing/components/custom/register-custom-component.tsx","../../src/lib/user-facing/components/html/html-property-panels.ts","../../src/lib/user-facing/components/html/register-html-elements.ts","../../src/lib/internal-details/handle-bootstrap-response.ts","../../src/lib/internal-details/internal-components/spinner.tsx","../../src/lib/internal-details/lib/features/injected-features.ts","../../src/lib/internal-details/use-api.ts","../../src/edit-mode/build-error-notification.tsx","../../src/edit-mode/create-component.ts","../../src/edit-mode/features/ai-store.ts","../../src/edit-mode/features/connection-manager.ts","../../src/edit-mode/async-socket.ts","../../src/edit-mode/source-update-api.ts","../../src/edit-mode/features/operation-store.ts","../../src/edit-mode/features/properties-panel-manager.ts","../../src/edit-mode/runtime-graph/observable-graph.ts","../../src/edit-mode/runtime-graph/runtime-component-node.ts","../../src/edit-mode/features/runtime-tracking-store.ts","../../src/edit-mode/features/resizing-store.ts","../../src/edit-mode/features/ui-store.ts","../../src/edit-mode/runtime-sync/builders.ts","../../src/edit-mode/runtime-sync/runtime-subscriptions-store.ts","../../src/edit-mode/edit-store.ts","../../src/lib/hooks/use-editor-hotkeys.ts","../../src/lib/hooks/use-key-pressed.ts","../../src/lib/hooks/use-observer-memo.ts","../../src/lib/user-facing/layers.ts","../../src/edit-mode/interaction-utils.ts","../../src/edit-mode/interaction-layer/interaction-rect-name-pill.tsx","../../src/edit-mode/interaction-layer/interaction-rect-actions.tsx","../../src/edit-mode/interaction-layer/transform-utils.ts","../../src/edit-mode/interaction-layer/interaction-rect.tsx","../../src/edit-mode/editor-hotkeys.tsx","../../src/edit-mode/screenshot-handler.ts","../../src/edit-mode/iframe-wrappers.tsx","../../src/lib/internal-details/lib/throttle.ts","../../src/edit-mode/extended-clickable-area.ts","../../src/edit-mode/interaction-layer/get-widgets-from-point.ts","../../src/edit-mode/interaction-layer/interaction-layer.tsx","../../src/lib/internal-details/app-wrappers.tsx","../../src/lib/internal-details/internal-components/error-boundary/index.tsx","../../src/lib/internal-details/lib/devtools/index.tsx","../../src/lib/internal-details/routing.ts","../../src/lib/user-facing/sb-provider-tracker.ts","../../src/lib/user-facing/styling/styles.ts","../../src/lib/user-facing/sb-provider.tsx","../../src/lib/user-facing/components/app/editor.ts","../../src/lib/user-facing/components/app/props.ts","../../src/lib/user-facing/components/app/index.tsx","../../src/lib/user-facing/error-pages/constants.ts","../../src/lib/user-facing/assets/images/errors/403-image.svg","../../src/lib/user-facing/assets/images/errors/404-image.svg","../../src/lib/user-facing/assets/images/errors/500-image.svg","../../src/lib/user-facing/assets/images/errors/general-error.svg","../../src/lib/user-facing/assets/images/errors/login-error.svg","../../src/lib/user-facing/error-pages/error-component.tsx","../../src/lib/user-facing/error-pages/page-not-found.tsx","../../src/lib/internal-details/internal-components/route-load-error.tsx","../../src/lib/index.ts"],"sourcesContent":["import { getEditStore } from \"../../edit-mode/get-edit-store.js\";\nimport {\n createManagedPropsList,\n createInternalPropsList,\n} from \"../user-facing/properties-panel/create-managed-props-list.js\";\nimport rootStore from \"./lib/root-store.js\";\nimport type { DefaultTagNames } from \"./lib/features/component-registry.js\";\nimport type {\n ExternalProps,\n PropertiesDefinition,\n RawPropsToExternal,\n} from \"../user-facing/properties-panel/props-builder.js\";\nimport type { DataTypeString } from \"@superblocksteam/library-shared/props\";\nimport type {\n AnonymousSbEntity,\n CreateChild,\n PropertyInfo,\n Catalog,\n EditorConfig,\n} from \"@superblocksteam/library-shared/types\";\nimport type React from \"react\";\nimport type { LegacyRef } from \"react\";\n\nexport type InjectedProps = {\n dropTargetRef?: React.Ref<HTMLElement> | LegacyRef<HTMLElement>;\n};\n\nexport type ParentInfo = {\n type?: string;\n};\n\nexport interface CreationContext {\n parentInfo: ParentInfo;\n defaultTagNames: DefaultTagNames;\n selfTagName: string;\n generateUniqueName: (prefix: string) => string;\n}\n\nexport type PropertyValues<P extends React.ComponentProps<any>> = {\n [K in keyof P]?: PropertyInfo | PropertyValues<P[K]>;\n};\n\nexport interface EditorTemplate<\n P extends React.ComponentProps<any> = React.ComponentProps<any>,\n> {\n catalog?: Catalog;\n /***\n * Config for the newly created component when added to the canvas from the Editor.\n * @returns a single CreateRequest or an array of CreateRequests.\n *\n * When returning Array<CreateRequests>:\n * - The 1st CreateRequest's type must match the componentType passed to createComponent.\n * - The last CreateRequest's will be the selected component after drag & drop.\n *\n * Example: [Modal, Button]\n * A modal that when drag & dropped on the page will add a trigger button.\n * The modal is closed by default, so the selected component after drop will be the trigger button.\n */\n create?: (\n context: CreationContext,\n ) => CreateRequest<P> | Array<CreateRequest<P>>;\n}\nexport interface CreateRequest<\n P extends React.ComponentProps<any> = React.ComponentProps<any>,\n> {\n type: string;\n properties?: PropertyValues<P>;\n createAt?: \"root\" | \"dropLocation\"; // default is \"dropLocation\"\n children?: CreateChild[];\n}\n\n// Chainable component interface\nexport interface Chainable<\n PROPS extends React.ComponentProps<any> = React.ComponentProps<any>,\n> {\n addEditorTemplate: (config: EditorTemplate<PROPS>) => Chainable<PROPS>;\n editorConfig: (config: EditorConfig) => Chainable<PROPS>;\n}\n\n/**\n * Register a component to be used with the framework.\n *\n * @param Component - The React component or HTML element name (e.g., \"div\") to register. Can be a React functional component, class component, or intrinsic element string.\n * @param propertiesDefinition - The definition of the component's properties, used for property panel generation and validation.\n *\n * @returns A chainable object that provides methods for editor integration (addEditorTemplate and editorConfig).\n */\nexport const registerComponentInternal = <T extends React.ElementType>(\n Component: T,\n propertiesDefinition: PropertiesDefinition,\n): Chainable<React.ComponentProps<T>> => {\n const type =\n typeof Component === \"string\"\n ? Component\n : Component.displayName || Component.name;\n\n if (!type) {\n throw new Error(\n `Component must have a name or displayName property, or be a string. Received: ${Component}`,\n );\n }\n\n const managedProps = createManagedPropsList(propertiesDefinition);\n\n // Syntactic sugar to set isDroppable to true when the component has children\n const isDroppable = !!managedProps.find(\n (p) => p.path === \"children\" && p.dataType === (\"jsx\" as DataTypeString),\n );\n\n rootStore.onEditorRegistered(() => {\n getEditStore().propertiesPanelManager.setPropertiesDefinition(\n type,\n propertiesDefinition,\n );\n });\n\n rootStore.componentRegistry.addComponent(\n type,\n Component,\n propertiesDefinition,\n );\n rootStore.componentRegistry.addManagedProps(type, managedProps ?? []);\n\n const defaultEditorConfig: EditorConfig = {};\n\n // TODO: This is only necessary on edit-mode\n if (isDroppable) {\n defaultEditorConfig.isDroppable = true;\n rootStore.componentRegistry.addEditorConfig(type, defaultEditorConfig);\n }\n\n // Return chainable object for editor configuration\n const chainableComponent: Chainable<React.ComponentProps<T>> = {\n addEditorTemplate: (\n templateConfig: EditorTemplate<React.ComponentProps<T>>,\n ): Chainable<React.ComponentProps<T>> => {\n const catalog: Catalog = templateConfig.catalog ?? {\n displayName: type,\n category: \"MISC\",\n };\n rootStore.componentRegistry.addEditorTemplate(type, {\n ...templateConfig,\n catalog,\n });\n return chainableComponent;\n },\n editorConfig: (\n config: EditorConfig,\n ): Chainable<React.ComponentProps<T>> => {\n rootStore.componentRegistry.addEditorConfig(type, {\n ...defaultEditorConfig,\n ...config,\n });\n return chainableComponent;\n },\n };\n\n return chainableComponent;\n};\n\nexport function registerEntity<\n PROPS,\n PD extends PropertiesDefinition,\n EP extends ExternalProps<PD> = ExternalProps<PD>,\n>(\n name: string,\n config: { propertiesDefinition: PD },\n Entity: (args: RawPropsToExternal<PROPS>) => EP & AnonymousSbEntity,\n): (args: RawPropsToExternal<PROPS>) => EP & AnonymousSbEntity {\n const managedProps = createManagedPropsList(config.propertiesDefinition);\n const internalProps = createInternalPropsList(config.propertiesDefinition);\n\n rootStore.componentRegistry.addManagedProps(name, managedProps ?? []);\n rootStore.componentRegistry.addInternalProps(name, internalProps ?? []);\n\n rootStore.onEditorRegistered(() => {\n getEditStore().propertiesPanelManager.setPropertiesDefinition(\n name,\n config.propertiesDefinition,\n );\n });\n\n return Entity;\n}\n","import { Prop, PropsCategory, Section } from \"../props-builder.js\";\n\n/**\n * Creates a standardized inline styles section for use in properties panels.\n * This provides a consistent interface for applying inline CSS styles across components.\n *\n * @param options - Configuration options to override defaults\n * @returns A Section with PropsCategory.Styles containing a style prop\n */\nexport const inlineStylesCategory = (\n options: Parameters<ReturnType<typeof Prop.any>[\"propertiesPanel\"]>[0] = {},\n): Section<{ style: React.CSSProperties }> => {\n const styleProp = Prop.any().propertiesPanel({\n label: \"Inline Styles\",\n controlType: \"INLINE_STYLE_BUILDER\" as const,\n description: \"Custom inline CSS styles\",\n isRemovable: true,\n defaultOnAdd: {},\n collapsibleHeader: true,\n ...options,\n });\n\n // Hide this property if there are no styles\n const originalToDefinition = styleProp.toDefinition.bind(styleProp);\n styleProp.toDefinition = function (props: Record<string, unknown>) {\n const styleValue = props?.style;\n\n if (\n !styleValue ||\n (typeof styleValue === \"string\" && styleValue.trim() === \"\") ||\n (typeof styleValue === \"object\" &&\n !Array.isArray(styleValue) &&\n Object.keys(styleValue).length === 0)\n ) {\n return undefined;\n }\n\n return originalToDefinition(props);\n };\n\n return Section.category(PropsCategory.Styles)\n .children({\n style: styleProp,\n })\n .propertiesPanel({\n showHeader: false,\n });\n};\n","let cachedRootFontSize: number | undefined = undefined;\nconst getRootFontSize = () => {\n // Memoized value\n if (cachedRootFontSize !== undefined) {\n return cachedRootFontSize;\n }\n\n if (typeof window !== \"undefined\" && typeof document !== \"undefined\") {\n try {\n const rootFontSize = window.getComputedStyle(\n document.documentElement,\n ).fontSize;\n const parsed = parseFloat(rootFontSize);\n if (!isNaN(parsed) && parsed > 0) {\n // Only cache if we successfully parsed a valid number\n cachedRootFontSize = parsed;\n return cachedRootFontSize;\n }\n } catch {\n console.error(\"Error getting root font size, using fallback of 16px\");\n }\n }\n return 16; // Fallback to default\n};\n\n/**\n * Converts CSS values with rem units to pixel values.\n * Uses the actual computed root font size from the browser.\n *\n * @param value - CSS value (e.g., \"1rem\", \"16px\", \"0.25rem\")\n * @returns Converted value in pixels if input was in rem, otherwise returns original value\n *\n * @example\n * convertRemToPixels(\"1rem\") // \"16px\" (assuming default root font size)\n * convertRemToPixels(\"0.5rem\") // \"8px\"\n * convertRemToPixels(\"16px\") // \"16px\" (unchanged)\n * convertRemToPixels(\"100%\") // \"100%\" (unchanged)\n */\nexport function convertRemToPixels(value: string): string {\n const remMatch = value.match(/^([\\d.]+)rem$/);\n if (!remMatch) {\n return value;\n }\n\n const remValue = parseFloat(remMatch[1]);\n const rootFontSize = getRootFontSize();\n const pixelValue = remValue * rootFontSize;\n\n // Round to avoid floating point precision issues for common values\n // e.g., 0.25 * 16 = 4.0 instead of 3.9999999\n const rounded =\n Math.abs(pixelValue - Math.round(pixelValue)) < 0.0001\n ? Math.round(pixelValue)\n : pixelValue;\n\n return `${rounded}px`;\n}\n","import postcss from \"postcss\";\n\ninterface ExtractedVariables {\n root: Record<string, string>;\n dark: Record<string, string>;\n theme: Record<string, string>;\n}\n\nasync function extractCSSVariablesFromContent(\n cssContent: string,\n): Promise<ExtractedVariables> {\n const variables: ExtractedVariables = {\n root: {},\n dark: {},\n theme: {},\n };\n\n try {\n const extractVariablesPlugin = () => {\n return {\n postcssPlugin: \"extract-variables\",\n Once(root: postcss.Root) {\n root.walkRules((rule) => {\n if (rule.selector === \":root\") {\n rule.walkDecls((decl) => {\n if (decl.prop.startsWith(\"--\")) {\n variables.root[decl.prop] = decl.value;\n }\n });\n } else if (rule.selector === \".dark\") {\n rule.walkDecls((decl) => {\n if (decl.prop.startsWith(\"--\")) {\n variables.dark[decl.prop] = decl.value;\n }\n });\n }\n });\n\n // Extract from @theme inline\n root.walkAtRules(\"theme\", (atRule) => {\n if (atRule.params === \"inline\") {\n atRule.walkDecls((decl) => {\n if (decl.prop.startsWith(\"--\")) {\n variables.theme[decl.prop] = decl.value;\n }\n });\n }\n });\n },\n };\n };\n\n extractVariablesPlugin.postcssPlugin = \"extract-variables\";\n\n await postcss([extractVariablesPlugin()]).process(cssContent, {\n from: undefined,\n });\n\n return variables;\n } catch (error) {\n throw new Error(\n `Failed to extract CSS variables: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n}\n\nasync function extractCSSVariables(): Promise<ExtractedVariables> {\n const styleSheets = Array.from(document.styleSheets);\n let cssContent = \"\";\n\n for (const sheet of styleSheets) {\n try {\n const text = Array.from(sheet.cssRules || [])\n .map((rule) => rule.cssText)\n .join(\"\\n\");\n cssContent += text;\n } catch (e) {\n // Cross-origin stylesheets will throw - skip them\n console.warn(\"Cannot access stylesheet:\", sheet.href, e);\n }\n }\n\n return extractCSSVariablesFromContent(cssContent);\n}\n\n// Global cache that persists across module reloads (for HMR)\ndeclare global {\n var __CSS_VARIABLES_CACHE__: ExtractedVariables | undefined;\n var __CSS_VARIABLES_LOADING__: boolean | undefined;\n var __CSS_VARIABLES_PROMISE__: Promise<ExtractedVariables> | undefined;\n}\n\n// Synchronous getter that returns cached variables or null if not loaded yet\nexport function getCachedCSSVariables(): ExtractedVariables | null {\n return globalThis.__CSS_VARIABLES_CACHE__ || null;\n}\n\n// Initialize CSS variables with proper global caching\nexport async function initializeCSSVariables(): Promise<ExtractedVariables> {\n // If already loaded, return cached version\n if (globalThis.__CSS_VARIABLES_CACHE__) {\n return globalThis.__CSS_VARIABLES_CACHE__;\n }\n\n // If currently loading, return the existing promise\n if (\n globalThis.__CSS_VARIABLES_LOADING__ &&\n globalThis.__CSS_VARIABLES_PROMISE__\n ) {\n return globalThis.__CSS_VARIABLES_PROMISE__;\n }\n\n // Start loading\n globalThis.__CSS_VARIABLES_LOADING__ = true;\n globalThis.__CSS_VARIABLES_PROMISE__ = extractCSSVariables()\n .then((variables) => {\n globalThis.__CSS_VARIABLES_CACHE__ = variables;\n globalThis.__CSS_VARIABLES_LOADING__ = false;\n return variables;\n })\n .catch((error) => {\n console.error(\"Failed to extract CSS variables:\", error);\n const fallback = { root: {}, dark: {}, theme: {} };\n globalThis.__CSS_VARIABLES_CACHE__ = fallback;\n globalThis.__CSS_VARIABLES_LOADING__ = false;\n return fallback;\n });\n\n return globalThis.__CSS_VARIABLES_PROMISE__;\n}\n","import colors from \"tailwindcss/colors\";\nimport defaultTheme from \"tailwindcss/defaultTheme\";\nimport { convertRemToPixels } from \"./convert-rem-to-pixels.js\";\nimport { getCachedCSSVariables } from \"./extract-variables.js\";\nimport type { ThemeToken } from \"@superblocksteam/library-shared/props\";\n\n// Cache for size presets to avoid recalculation\nlet cachedSizePresets: {\n height: ThemeToken[];\n width: ThemeToken[];\n spacing: ThemeToken[];\n} | null = null;\n\nconst height = defaultTheme.height({ theme: () => \"\", colors });\nconst width = defaultTheme.width({ theme: () => \"\", colors });\nconst minWidth = defaultTheme.minWidth({ theme: () => \"\", colors });\nconst maxWidth = defaultTheme.maxWidth({ theme: () => \"\", colors });\nconst minHeight = defaultTheme.minHeight({ theme: () => \"\", colors });\nconst maxHeight = defaultTheme.maxHeight({ theme: () => \"\", colors });\nconst spacing = defaultTheme.spacing;\n// Helper function to detect if a value looks like a size\nexport function isSizeValue(value: string): boolean {\n const trimmedValue = value.trim().toLowerCase();\n\n // Check for common size formats\n return (\n // Pixel values\n /^\\d+px$/.test(trimmedValue) ||\n // Rem values\n /^\\d+(\\.\\d+)?rem$/.test(trimmedValue) ||\n // Em values\n /^\\d+(\\.\\d+)?em$/.test(trimmedValue) ||\n // Percentage values\n /^\\d+(\\.\\d+)?%$/.test(trimmedValue) ||\n // Viewport units\n /^\\d+(\\.\\d+)?(vw|vh|vmin|vmax|dvw|dvh|lvw|lvh|svw|svh)$/.test(\n trimmedValue,\n ) ||\n // Fractional units\n /^\\d+(\\.\\d+)?(fr|ch|ex|ic|cap|lh|rlh)$/.test(trimmedValue) ||\n // CSS keywords\n [\n \"auto\",\n \"inherit\",\n \"initial\",\n \"unset\",\n \"revert\",\n \"revert-layer\",\n \"max-content\",\n \"min-content\",\n \"fit-content\",\n \"stretch\",\n \"none\",\n \"0\",\n \"1\",\n \"2\",\n \"3\",\n \"4\",\n \"5\",\n \"6\",\n \"7\",\n \"8\",\n \"9\",\n \"10\",\n \"11\",\n \"12\",\n \"14\",\n \"16\",\n \"20\",\n \"24\",\n \"28\",\n \"32\",\n \"36\",\n \"40\",\n \"44\",\n \"48\",\n \"52\",\n \"56\",\n \"60\",\n \"64\",\n \"72\",\n \"80\",\n \"96\",\n ].includes(trimmedValue)\n );\n}\n\nexport function getSizePresets() {\n if (cachedSizePresets) {\n return cachedSizePresets;\n }\n\n const cssVariables = getCachedCSSVariables();\n if (!cssVariables) {\n return [];\n }\n\n const sizePresets: ThemeToken[] = [];\n\n const addCssSize = (prop: string, value: string) => {\n if (isSizeValue(value)) {\n const label = prop.replace(\"--\", \"\").replace(/-/g, \" \");\n sizePresets.push({\n label,\n value: `(${prop})`,\n rawValue: convertRemToPixels(value),\n type: \"system\" as const,\n });\n }\n };\n\n // Extract size variables from root\n for (const [prop, value] of Object.entries(cssVariables.root)) {\n addCssSize(prop, value);\n }\n\n // Extract size variables from theme\n for (const [prop, value] of Object.entries(cssVariables.theme)) {\n addCssSize(prop, value);\n }\n\n // Extract size variables from dark theme\n for (const [prop, value] of Object.entries(cssVariables.dark)) {\n addCssSize(prop, value);\n }\n\n // add spacing to size presets\n for (const [key, value] of Object.entries(spacing)) {\n sizePresets.push({\n label: key,\n value: key,\n rawValue: convertRemToPixels(value),\n type: \"tailwind\" as const,\n });\n }\n\n const allWidth = { ...width, ...minWidth, ...maxWidth };\n const allHeight = { ...height, ...minHeight, ...maxHeight };\n\n const heightPresets = [...sizePresets];\n const widthPresets = [...sizePresets];\n for (const [key, value] of Object.entries(allWidth)) {\n if (typeof value === \"string\") {\n widthPresets.push({\n label: key,\n value: key,\n rawValue: convertRemToPixels(value),\n type: \"tailwind\" as const,\n });\n }\n }\n\n // Add Tailwind CSS default height values\n for (const [key, value] of Object.entries(allHeight)) {\n if (typeof value === \"string\") {\n heightPresets.push({\n label: key,\n value: key,\n rawValue: convertRemToPixels(value),\n type: \"tailwind\" as const,\n });\n }\n }\n\n // Remove duplicates\n const seen = new Set<string>();\n const uniqueHeightPresets = heightPresets.filter((preset) => {\n if (seen.has(preset.value)) return false;\n seen.add(preset.value);\n return true;\n });\n\n seen.clear();\n const uniqueWidthPresets = widthPresets.filter((preset) => {\n if (seen.has(preset.value)) return false;\n seen.add(preset.value);\n return true;\n });\n\n seen.clear();\n const uniqueSpacingPresets = sizePresets.filter((preset) => {\n if (seen.has(preset.value)) return false;\n seen.add(preset.value);\n return true;\n });\n\n cachedSizePresets = {\n height: uniqueHeightPresets,\n width: uniqueWidthPresets,\n spacing: uniqueSpacingPresets,\n };\n return cachedSizePresets;\n}\n","import defaultTheme from \"tailwindcss/defaultTheme\";\nimport { convertRemToPixels } from \"./convert-rem-to-pixels.js\";\nimport { getCachedCSSVariables } from \"./extract-variables.js\";\nimport { isSizeValue } from \"./style-tokens-size.js\";\nimport type { ThemeToken } from \"@superblocksteam/library-shared/props\";\n\n// Cache for size presets to avoid recalculation\nlet cachedBorderPresets: {\n borderWidth: ThemeToken[];\n borderRadius: ThemeToken[];\n boxShadow: ThemeToken[];\n} | null = null;\n\nconst borderWidth = defaultTheme.borderWidth;\nconst borderRadius = defaultTheme.borderRadius;\nconst boxShadow = defaultTheme.boxShadow;\n\nconst DEFAULT_KEY = \"DEFAULT\";\n\n// Helper function to detect if a value looks like a box shadow\nfunction isBoxShadowValue(value: string): boolean {\n const trimmedValue = value.trim().toLowerCase();\n const isBoxShadow =\n /^(0|none|inset|outset|shadow-sm|shadow|shadow-md|shadow-lg|shadow-xl|shadow-2xl|shadow-inner|shadow-none)$/.test(\n trimmedValue,\n );\n if (isBoxShadow) {\n return true;\n }\n // Box shadow format: [inset?] [x] [y] [blur?] [spread?] [color?]\n // Can have multiple comma-separated shadows\n const customBoxShadowPattern =\n /^(inset\\s+)?(-?\\d+(\\.\\d+)?(px|rem|em|%)?(\\s+|$)){2,4}([a-z]+\\(.*?\\)|#[0-9a-f]{3,8}|[a-z]+)?(\\s*,\\s*(inset\\s+)?(-?\\d+(\\.\\d+)?(px|rem|em|%)?(\\s+|$)){2,4}([a-z]+\\(.*?\\)|#[0-9a-f]{3,8}|[a-z]+)?)*$/i;\n\n return isBoxShadow || customBoxShadowPattern.test(trimmedValue);\n}\n\n// Helper function to format label - lowercases the text\nfunction formatLabel(key: string): string {\n return key.toLowerCase();\n}\n\nexport function getBorderPresets() {\n if (cachedBorderPresets) {\n return cachedBorderPresets;\n }\n\n const cssVariables = getCachedCSSVariables();\n if (!cssVariables) {\n return [];\n }\n\n const sizePresets: ThemeToken[] = [];\n const boxShadowPresets: ThemeToken[] = [];\n\n const addCssSize = (prop: string, value: string) => {\n if (isSizeValue(value)) {\n const label = formatLabel(prop.replace(\"--\", \"\").replace(/-/g, \" \"));\n sizePresets.push({\n label,\n value: `(${prop})`,\n rawValue: convertRemToPixels(value),\n type: \"system\" as const,\n });\n } else if (isBoxShadowValue(value)) {\n const label = formatLabel(prop.replace(\"--\", \"\").replace(/-/g, \" \"));\n boxShadowPresets.push({\n label,\n value: `(${prop})`,\n rawValue: value,\n type: \"system\" as const,\n });\n }\n };\n\n // Extract svariables from root\n for (const [prop, value] of Object.entries(cssVariables.root)) {\n addCssSize(prop, value);\n }\n\n // Extract variables from theme\n for (const [prop, value] of Object.entries(cssVariables.theme)) {\n addCssSize(prop, value);\n }\n\n // Extract variables from dark theme\n for (const [prop, value] of Object.entries(cssVariables.dark)) {\n addCssSize(prop, value);\n }\n // add things from the theme to each of the presets\n const borderWidthPresets = [...sizePresets];\n const borderRadiusPresets = [...sizePresets];\n\n function addTailwindProperty(\n presets: ThemeToken[],\n key: string,\n value: unknown,\n valueConverter?: (value: string) => string,\n ) {\n if (key === DEFAULT_KEY && typeof value === \"string\") {\n presets.push({\n label: \"default\",\n value: \"\", // empty string (i.e. \"border\" or \"rounded\")\n rawValue: valueConverter\n ? valueConverter(value)\n : convertRemToPixels(value),\n type: \"tailwind\" as const,\n });\n } else if (typeof value === \"string\") {\n presets.push({\n label: formatLabel(key),\n value: key,\n rawValue: valueConverter\n ? valueConverter(value)\n : convertRemToPixels(value),\n type: \"tailwind\" as const,\n });\n }\n }\n\n for (const [key, value] of Object.entries(borderWidth)) {\n addTailwindProperty(borderWidthPresets, key, value, convertRemToPixels);\n }\n\n for (const [key, value] of Object.entries(borderRadius)) {\n addTailwindProperty(borderRadiusPresets, key, value, convertRemToPixels);\n }\n\n for (const [key, value] of Object.entries(boxShadow)) {\n addTailwindProperty(boxShadowPresets, key, value);\n }\n\n // Remove duplicates\n const seen = new Set<string>();\n const uniqueBorderWidthPresets = borderWidthPresets.filter((preset) => {\n if (seen.has(preset.value)) return false;\n seen.add(preset.value);\n return true;\n });\n\n seen.clear();\n const uniqueBorderRadiusPresets = borderRadiusPresets.filter((preset) => {\n if (seen.has(preset.value)) return false;\n seen.add(preset.value);\n return true;\n });\n\n seen.clear();\n const uniqueBoxShadowPresets = boxShadowPresets.filter((preset) => {\n if (seen.has(preset.value)) return false;\n seen.add(preset.value);\n return true;\n });\n\n cachedBorderPresets = {\n borderWidth: uniqueBorderWidthPresets,\n borderRadius: uniqueBorderRadiusPresets,\n boxShadow: uniqueBoxShadowPresets,\n };\n return cachedBorderPresets;\n}\n","import colors from \"tailwindcss/colors\";\nimport { getCachedCSSVariables } from \"./extract-variables.js\";\nimport type { ThemeToken } from \"@superblocksteam/library-shared/props\";\n\n// Cache for color presets to avoid recalculation\nlet cachedColorPresets: ThemeToken[] | null = null;\n\n// Helper function to detect if a value looks like a color\nfunction isColorValue(value: string): boolean {\n const trimmedValue = value.trim().toLowerCase();\n\n // Check for common color formats\n return (\n trimmedValue.startsWith(\"#\") || // Hex colors\n trimmedValue.startsWith(\"rgb(\") || // RGB\n trimmedValue.startsWith(\"rgba(\") || // RGBA\n trimmedValue.startsWith(\"hsl(\") || // HSL\n trimmedValue.startsWith(\"hsla(\") || // HSLA\n trimmedValue.startsWith(\"oklch(\") || // OKLCH\n trimmedValue.startsWith(\"oklab(\") || // OKLAB\n trimmedValue.startsWith(\"lch(\") || // LCH\n trimmedValue.startsWith(\"lab(\") || // LAB\n trimmedValue.startsWith(\"color(\") || // CSS Color Module Level 4\n trimmedValue.startsWith(\"hwb(\") || // HWB\n // Common CSS color keywords\n [\n \"transparent\",\n \"currentcolor\",\n \"inherit\",\n \"initial\",\n \"unset\",\n \"red\",\n \"blue\",\n \"green\",\n \"black\",\n \"white\",\n \"gray\",\n \"yellow\",\n \"orange\",\n \"purple\",\n \"pink\",\n \"brown\",\n ].includes(trimmedValue)\n );\n}\n\nexport function getColorPresets() {\n if (cachedColorPresets) {\n return cachedColorPresets;\n }\n\n const cssVariables = getCachedCSSVariables();\n if (!cssVariables) {\n return [];\n }\n\n const colorPresets = [];\n\n const addCssColor = (prop: string, value: string) => {\n if (isColorValue(value)) {\n const label = prop.replace(\"--\", \"\").replace(/-/g, \" \");\n colorPresets.push({\n label,\n value: prop.replace(\"--\", \"\"),\n rawValue: value,\n type: \"system\" as const,\n });\n }\n };\n\n // Extract color variables from root\n for (const [prop, value] of Object.entries(cssVariables.root)) {\n addCssColor(prop, value);\n }\n\n // Extract color variables from theme\n for (const [prop, value] of Object.entries(cssVariables.theme)) {\n addCssColor(prop, value);\n }\n\n // from dark colors\n for (const [prop, value] of Object.entries(cssVariables.dark)) {\n addCssColor(prop, value);\n }\n\n // Add Tailwind CSS default colors\n for (const [colorName, colorShades] of Object.entries(colors)) {\n if (typeof colorShades === \"object\" && colorShades !== null) {\n // Handle color objects with shades (like red.100, red.200, etc.)\n for (const [shade, colorValue] of Object.entries(colorShades)) {\n if (typeof colorValue === \"string\") {\n colorPresets.push({\n label: `${colorName} ${shade}`,\n value: `${colorName}-${shade}`,\n rawValue: colorValue,\n type: \"tailwind\" as const,\n });\n }\n }\n } else if (typeof colorShades === \"string\") {\n // Handle single color values (like transparent, current, etc.)\n colorPresets.push({\n label: colorName,\n value: colorName,\n rawValue: colorShades,\n type: \"tailwind\" as const,\n });\n }\n }\n\n // Remove duplicates\n const seen = new Set<string>();\n const uniquePresets = colorPresets.filter((preset) => {\n if (seen.has(preset.value)) return false;\n seen.add(preset.value);\n return true;\n });\n\n cachedColorPresets = uniquePresets;\n return uniquePresets;\n}\n","import { Prop, PropsCategory, Section } from \"../props-builder.js\";\nimport { getBorderPresets } from \"./style-tokens-border.js\";\nimport { getColorPresets } from \"./style-tokens-color.js\";\nimport { getSizePresets } from \"./style-tokens-size.js\";\nimport type { TailwindPropertyKey } from \"@superblocksteam/library-shared\";\n\n/**\n * Creates a standardized styles section for use in properties panels.\n * This provides a consistent interface for applying Tailwind CSS classes across components.\n *\n * @example\n * // Basic usage with defaults\n * styles: tailwindStylesCategory()\n *\n * // Override with prioritizedTailwindProperties. These properties will always be shown in the properties panel, event when not set.\n * styles: tailwindStylesCategory({prioritizedTailwindProperties: [\"rounded\", \"text-color\"]})\n *\n * @param options - Configuration options to override defaults\n * @returns A Section with PropsCategory.Styles containing a className prop\n */\nexport const tailwindStylesCategory = (props?: {\n prioritizedTailwindProperties?: TailwindPropertyKey[];\n}): Section<{ className: string }> => {\n const { prioritizedTailwindProperties } = props ?? {};\n return Section.category(PropsCategory.Appearance).children({\n className: Prop.string().propertiesPanel({\n controlType: \"TAILWIND_CLASS_BUILDER\" as const,\n themePresets: function () {\n return {\n ...getSizePresets(),\n ...getBorderPresets(),\n colors: getColorPresets(),\n };\n },\n prioritizedTailwindProperties,\n }),\n });\n};\n","import { registerComponentInternal } from \"../../internal-index.js\";\nimport { inlineStylesCategory } from \"../../properties-panel/mixins/inline-styles-category.js\";\nimport { tailwindStylesCategory } from \"../../properties-panel/mixins/styles-category.js\";\nimport {\n Section,\n PropsCategory,\n type SectionPropRecord,\n} from \"../../properties-panel/props-builder.js\";\nimport type { Prop } from \"../../properties-panel/props-builder.js\";\nimport type React from \"react\";\n\nexport type PropertiesPanelDefinition<Props extends React.ComponentProps<any>> =\n\n | SectionPropRecord<Props>\n | {\n [K in string]: Section<Props, SectionPropRecord<Props>>;\n };\n\nconst defaultSectionsTemplate = () => ({\n appearance: tailwindStylesCategory(),\n styles: inlineStylesCategory(),\n});\n\nfunction convertToSections(\n propertiesDefinition: Record<string, Prop<any>>,\n): Record<string, Section<any, any>> {\n const contentSection = Section.category(PropsCategory.Content).children(\n Object.fromEntries(\n Object.entries(propertiesDefinition).filter(\n ([, prop]) => prop.type !== \"eventHandler\",\n ),\n ),\n );\n\n const eventSection = Section.category(PropsCategory.EventHandlers).children(\n Object.fromEntries(\n Object.entries(propertiesDefinition).filter(\n ([, prop]) => prop.type === \"eventHandler\",\n ),\n ),\n );\n\n return {\n content: contentSection,\n events: eventSection,\n };\n}\n\nfunction mergeSections(\n sections: Record<string, Section<any, any>>,\n defaultSections: Record<string, Section<any, any>>,\n): Record<string, Section<any, any>> {\n const allCurrentProps = Object.values(sections).flatMap((section) =>\n Object.keys(section.props),\n );\n\n Object.entries(defaultSections).forEach(([sectionName, section]) => {\n Object.entries(section.props).forEach(([propName, prop]) => {\n if (!allCurrentProps.includes(propName)) {\n if (!sections[sectionName]) {\n sections[sectionName] =\n defaultSections[sectionName as keyof typeof defaultSections];\n }\n sections[sectionName].add({ [propName]: prop } as Record<\n string,\n Prop<any>\n >);\n }\n });\n });\n\n return sections;\n}\n\n/**\n * Registers a custom React component or HTML element with Superblocks.\n *\n * @param component - The React component or HTML element name (e.g., \"div\") to register\n * @param propertiesDefinition - Optional properties panel definition, either as flat props or organized into sections\n * @returns The registered component\n *\n * @example\n * ```tsx\n * // Register HTML element with just defaults\n * registerComponent(\"div\");\n *\n * // Register HTML element with custom props\n * registerComponent(\"div\", {\n * children: Prop.node(),\n * onClick: Prop.eventHandler(),\n * });\n *\n * // Flat props (auto-categorized into Content and Event sections)\n * registerComponent(MyComponent, {\n * label: Prop.string().default(\"Click me\"),\n * onClick: Prop.eventHandler(),\n * });\n *\n * // Organized into sections\n * registerComponent(MyComponent, {\n * content: Section.category(PropsCategory.Content).children({\n * label: Prop.string().default(\"Click me\"),\n * }),\n * events: Section.category(PropsCategory.EventHandlers).children({\n * onClick: Prop.eventHandler(),\n * }),\n * });\n * ```\n */\nexport function registerComponent<T extends React.ElementType>(\n component: T,\n propertiesDefinition?: PropertiesPanelDefinition<React.ComponentProps<T>>,\n): ReturnType<typeof registerComponentInternal> {\n const defaultSections = defaultSectionsTemplate();\n\n // If no properties provided, just use defaults\n if (!propertiesDefinition) {\n return registerComponentInternal(component, defaultSections);\n }\n\n const containsSections = Object.values(propertiesDefinition).every(\n (prop) => prop instanceof Section,\n );\n\n const allSections = containsSections\n ? mergeSections(\n propertiesDefinition as Record<string, Section<any, any>>,\n defaultSections,\n )\n : mergeSections(\n convertToSections(propertiesDefinition as Record<string, Prop<any>>),\n defaultSections,\n );\n\n return registerComponentInternal(component, allSections);\n}\n","import { tailwindStylesCategory } from \"../../properties-panel/mixins/styles-category.js\";\nimport {\n Prop,\n PropsCategory,\n Section,\n} from \"../../properties-panel/props-builder.js\";\nimport type { PropertiesPanelDefinition } from \"../custom/register-custom-component.js\";\nimport type { TailwindPropertyKey } from \"@superblocksteam/library-shared\";\n\n// Typography-focused Tailwind properties that should be prioritized for text elements\nconst TYPOGRAPHY_PRIORITIZED_PROPERTIES: TailwindPropertyKey[] = [\n \"font-family\",\n \"font-size\",\n \"font-weight\",\n \"font-style\",\n \"line-height\",\n \"letter-spacing\",\n \"text-align\",\n \"text-color\",\n \"text-decoration\",\n \"text-transform\",\n];\n\n// Container-focused Tailwind properties that should be prioritized for container elements\nconst CONTAINER_PRIORITIZED_PROPERTIES: TailwindPropertyKey[] = [\n \"display\",\n // Spacing\n \"p\",\n \"m\",\n // Sizing\n \"width\",\n \"height\",\n // Background\n \"background-color\",\n // Borders (order matches UI: radius, width+color, style)\n \"rounded\",\n \"border-width\",\n \"border-style\",\n // Overflow\n \"overflow\",\n];\n\nexport const htmlTagSectionsTemplate = (params: {\n hasChildren: boolean;\n prioritizedTailwindProperties?: TailwindPropertyKey[];\n}): PropertiesPanelDefinition<React.ComponentProps<any>> => {\n const sections: PropertiesPanelDefinition<React.ComponentProps<any>> = {};\n\n // Add content section for elements with children\n if (params.hasChildren) {\n sections.contentSection = Section.category(PropsCategory.Content).children({\n children: Prop.jsx().propertiesPanel({\n label: \"Children\",\n description: \"The content of the element\",\n }),\n });\n }\n\n // Add styles section with optional prioritized properties\n sections.appearance = tailwindStylesCategory({\n prioritizedTailwindProperties: params.prioritizedTailwindProperties,\n });\n\n return sections;\n};\n\nexport const htmlTagSectionsTemplateForTypography =\n (): PropertiesPanelDefinition<React.ComponentProps<any>> => {\n return htmlTagSectionsTemplate({\n hasChildren: true,\n prioritizedTailwindProperties: TYPOGRAPHY_PRIORITIZED_PROPERTIES,\n });\n };\n\nexport const htmlTagSectionsTemplateForContainers =\n (): PropertiesPanelDefinition<React.ComponentProps<any>> => {\n return htmlTagSectionsTemplate({\n hasChildren: true,\n prioritizedTailwindProperties: CONTAINER_PRIORITIZED_PROPERTIES,\n });\n };\n","/**\n * Register all common HTML elements with default properties panels.\n * This enables all standard HTML elements to work seamlessly in the Superblocks editor\n * with automatic className and style properties.\n */\nimport { registerComponent } from \"../custom/register-custom-component.js\";\nimport {\n htmlTagSectionsTemplate,\n htmlTagSectionsTemplateForContainers,\n htmlTagSectionsTemplateForTypography,\n} from \"./html-property-panels.js\";\n\nlet registered = false;\n\n/**\n * Registers all standard HTML elements with default properties panels.\n * This is called automatically when the library is imported.\n */\nexport function registerHtmlElements() {\n // Only register once\n if (registered) {\n return;\n }\n registered = true;\n\n // Structural elements\n registerComponent(\"div\", htmlTagSectionsTemplateForContainers());\n registerComponent(\"section\", htmlTagSectionsTemplateForContainers());\n registerComponent(\"article\", htmlTagSectionsTemplateForContainers());\n registerComponent(\"header\", htmlTagSectionsTemplateForContainers());\n registerComponent(\"footer\", htmlTagSectionsTemplateForContainers());\n registerComponent(\"main\", htmlTagSectionsTemplateForContainers());\n registerComponent(\"aside\", htmlTagSectionsTemplateForContainers());\n registerComponent(\"nav\", htmlTagSectionsTemplateForContainers());\n registerComponent(\"address\", htmlTagSectionsTemplateForContainers());\n registerComponent(\"hgroup\", htmlTagSectionsTemplateForContainers());\n\n // Headings and text\n registerComponent(\"span\", htmlTagSectionsTemplateForTypography());\n registerComponent(\"h1\", htmlTagSectionsTemplateForTypography());\n registerComponent(\"h2\", htmlTagSectionsTemplateForTypography());\n registerComponent(\"h3\", htmlTagSectionsTemplateForTypography());\n registerComponent(\"h4\", htmlTagSectionsTemplateForTypography());\n registerComponent(\"h5\", htmlTagSectionsTemplateForTypography());\n registerComponent(\"h6\", htmlTagSectionsTemplateForTypography());\n registerComponent(\"p\", htmlTagSectionsTemplateForTypography());\n registerComponent(\"a\", htmlTagSectionsTemplateForTypography());\n registerComponent(\"strong\", htmlTagSectionsTemplateForTypography());\n registerComponent(\"em\", htmlTagSectionsTemplateForTypography());\n registerComponent(\"code\", htmlTagSectionsTemplateForTypography());\n registerComponent(\"pre\", htmlTagSectionsTemplateForTypography());\n registerComponent(\"blockquote\", htmlTagSectionsTemplateForTypography());\n registerComponent(\"abbr\", htmlTagSectionsTemplateForTypography());\n registerComponent(\"small\", htmlTagSectionsTemplateForTypography());\n registerComponent(\"mark\", htmlTagSectionsTemplateForTypography());\n registerComponent(\"del\", htmlTagSectionsTemplateForTypography());\n registerComponent(\"ins\", htmlTagSectionsTemplateForTypography());\n registerComponent(\"sub\", htmlTagSectionsTemplateForTypography());\n registerComponent(\"sup\", htmlTagSectionsTemplateForTypography());\n registerComponent(\"cite\", htmlTagSectionsTemplateForTypography());\n registerComponent(\"dfn\", htmlTagSectionsTemplateForTypography());\n registerComponent(\"kbd\", htmlTagSectionsTemplateForTypography());\n registerComponent(\"samp\", htmlTagSectionsTemplateForTypography());\n registerComponent(\"var\", htmlTagSectionsTemplateForTypography());\n registerComponent(\"s\", htmlTagSectionsTemplateForTypography());\n registerComponent(\"q\", htmlTagSectionsTemplateForTypography());\n registerComponent(\"u\", htmlTagSectionsTemplateForTypography());\n registerComponent(\"b\", htmlTagSectionsTemplateForTypography());\n registerComponent(\"i\", htmlTagSectionsTemplateForTypography());\n registerComponent(\"bdi\", htmlTagSectionsTemplateForTypography());\n registerComponent(\"bdo\", htmlTagSectionsTemplateForTypography());\n registerComponent(\"ruby\", htmlTagSectionsTemplateForTypography());\n registerComponent(\"rt\", htmlTagSectionsTemplateForTypography());\n registerComponent(\"rp\", htmlTagSectionsTemplateForTypography());\n\n // Form elements\n registerComponent(\"form\", htmlTagSectionsTemplate({ hasChildren: true }));\n registerComponent(\"input\", htmlTagSectionsTemplate({ hasChildren: false }));\n registerComponent(\"button\", htmlTagSectionsTemplateForTypography());\n registerComponent(\"textarea\", htmlTagSectionsTemplateForTypography());\n registerComponent(\"select\", htmlTagSectionsTemplate({ hasChildren: true }));\n registerComponent(\"option\", htmlTagSectionsTemplateForTypography());\n registerComponent(\"label\", htmlTagSectionsTemplateForTypography());\n registerComponent(\"fieldset\", htmlTagSectionsTemplate({ hasChildren: true }));\n registerComponent(\"legend\", htmlTagSectionsTemplateForTypography());\n registerComponent(\"datalist\", htmlTagSectionsTemplate({ hasChildren: true }));\n registerComponent(\"output\", htmlTagSectionsTemplate({ hasChildren: true }));\n registerComponent(\"progress\", htmlTagSectionsTemplate({ hasChildren: true }));\n registerComponent(\"meter\", htmlTagSectionsTemplate({ hasChildren: true }));\n\n // List elements\n registerComponent(\"ul\", htmlTagSectionsTemplate({ hasChildren: true }));\n registerComponent(\"ol\", htmlTagSectionsTemplate({ hasChildren: true }));\n registerComponent(\"li\", htmlTagSectionsTemplateForTypography());\n registerComponent(\"dl\", htmlTagSectionsTemplate({ hasChildren: true }));\n registerComponent(\"dt\", htmlTagSectionsTemplateForTypography());\n registerComponent(\"dd\", htmlTagSectionsTemplateForTypography());\n\n // Table elements\n registerComponent(\"table\", htmlTagSectionsTemplate({ hasChildren: true }));\n registerComponent(\"thead\", htmlTagSectionsTemplate({ hasChildren: true }));\n registerComponent(\"tbody\", htmlTagSectionsTemplate({ hasChildren: true }));\n registerComponent(\"tfoot\", htmlTagSectionsTemplate({ hasChildren: true }));\n registerComponent(\"tr\", htmlTagSectionsTemplate({ hasChildren: true }));\n registerComponent(\"th\", htmlTagSectionsTemplateForTypography());\n registerComponent(\"td\", htmlTagSectionsTemplateForTypography());\n registerComponent(\"caption\", htmlTagSectionsTemplateForTypography());\n registerComponent(\"colgroup\", htmlTagSectionsTemplate({ hasChildren: true }));\n registerComponent(\"col\", htmlTagSectionsTemplate({ hasChildren: false }));\n\n // Media elements\n registerComponent(\"img\", htmlTagSectionsTemplate({ hasChildren: false }));\n registerComponent(\"video\", htmlTagSectionsTemplate({ hasChildren: true }));\n registerComponent(\"audio\", htmlTagSectionsTemplate({ hasChildren: true }));\n registerComponent(\"source\", htmlTagSectionsTemplate({ hasChildren: false }));\n registerComponent(\"track\", htmlTagSectionsTemplate({ hasChildren: false }));\n registerComponent(\"canvas\", htmlTagSectionsTemplate({ hasChildren: true }));\n registerComponent(\"svg\", htmlTagSectionsTemplate({ hasChildren: true }));\n registerComponent(\"picture\", htmlTagSectionsTemplate({ hasChildren: true }));\n registerComponent(\"figure\", htmlTagSectionsTemplate({ hasChildren: true }));\n registerComponent(\n \"figcaption\",\n htmlTagSectionsTemplate({ hasChildren: true }),\n );\n\n // Embedded content\n registerComponent(\"iframe\", htmlTagSectionsTemplate({ hasChildren: true }));\n registerComponent(\"embed\", htmlTagSectionsTemplate({ hasChildren: false }));\n registerComponent(\"object\", htmlTagSectionsTemplate({ hasChildren: true }));\n registerComponent(\"param\", htmlTagSectionsTemplate({ hasChildren: false }));\n\n // Interactive elements\n registerComponent(\"details\", htmlTagSectionsTemplate({ hasChildren: true }));\n registerComponent(\"summary\", htmlTagSectionsTemplateForTypography());\n registerComponent(\"dialog\", htmlTagSectionsTemplate({ hasChildren: true }));\n registerComponent(\"menu\", htmlTagSectionsTemplate({ hasChildren: true }));\n\n // Miscellaneous\n registerComponent(\"hr\", htmlTagSectionsTemplate({ hasChildren: false }));\n registerComponent(\"br\", htmlTagSectionsTemplate({ hasChildren: false }));\n registerComponent(\"wbr\", htmlTagSectionsTemplate({ hasChildren: false }));\n registerComponent(\"time\", htmlTagSectionsTemplate({ hasChildren: true }));\n registerComponent(\"data\", htmlTagSectionsTemplate({ hasChildren: true }));\n registerComponent(\"template\", htmlTagSectionsTemplate({ hasChildren: true }));\n registerComponent(\"slot\", htmlTagSectionsTemplate({ hasChildren: true }));\n\n // Self-closing elements that don't accept children\n registerComponent(\"area\", htmlTagSectionsTemplate({ hasChildren: false }));\n registerComponent(\"base\", htmlTagSectionsTemplate({ hasChildren: false }));\n registerComponent(\"keygen\", htmlTagSectionsTemplate({ hasChildren: false }));\n registerComponent(\"link\", htmlTagSectionsTemplate({ hasChildren: false }));\n registerComponent(\"meta\", htmlTagSectionsTemplate({ hasChildren: false }));\n}\n","import rootStore from \"./lib/root-store.js\";\nimport type { IframeEventHandler } from \"./lib/iframe.js\";\n\nexport const handleBootstrapResponse: IframeEventHandler<\n \"sb-bootstrap-response\"\n> = (event) => {\n rootStore.applicationId = event.data.payload.appId;\n rootStore.userId = event.data.payload.userId;\n rootStore.apis.agentUrls =\n event.data.payload.agentUrls ??\n (event.data.payload.agentUrl ? [event.data.payload.agentUrl] : []);\n rootStore.apis.setTokens(\n event.data.payload.token,\n event.data.payload.accessToken,\n );\n\n rootStore.apis.notifyBootstrapComplete();\n\n const windowOriginUrl = event.data.payload.logContext\n .superblocks_window_origin_url as string;\n rootStore.windowOriginUrl = windowOriginUrl;\n\n if (rootStore.windowOriginUrl) {\n import(\"../utils.js\").then(({ initTracerProviderWithOrigin }) => {\n initTracerProviderWithOrigin(rootStore.windowOriginUrl!);\n\n // Initialize logging with full context\n import(\"../tracing/logs.js\").then(({ initLibraryLoggerProvider }) => {\n initLibraryLoggerProvider({\n windowOriginUrl: rootStore.windowOriginUrl!,\n appId: event.data.payload.appId,\n userId: event.data.payload.logContext.superblocks_user_id as string,\n userEmail: event.data.payload.logContext\n .superblocks_user_email as string,\n orgId: event.data.payload.logContext.superblocks_org_id as string,\n orgName: event.data.payload.logContext.superblocks_org_name as string,\n environment: event.data.payload.logContext.superblocks_env as string,\n });\n });\n });\n }\n};\n","import styled from \"styled-components\";\n\nexport const Spinner = styled.span`\n width: 50px;\n height: 50px;\n border: 4px solid #e0e1e5;\n border-bottom-color: #8c95a1;\n border-radius: 50%;\n display: inline-block;\n box-sizing: border-box;\n animation: rotation 0.5s linear infinite;\n\n @keyframes rotation {\n 0% {\n transform: rotate(0deg);\n }\n 100% {\n transform: rotate(360deg);\n }\n }\n`;\n\nexport const FullPageSpinner = () => {\n return (\n <div\n style={{\n display: \"flex\",\n justifyContent: \"center\",\n alignItems: \"center\",\n height: \"100svh\",\n width: \"100%\",\n }}\n >\n <Spinner />\n </div>\n );\n};\n","// import TokenProvider from \"../../TokenProvider\";\n\nimport { useMemo } from \"react\";\n\n// export const userApi = createApi({\n// reducerPath: \"userApi\",\n// baseQuery: fetchBaseQuery({\n// baseUrl: \"https://dev.superblocks.com/api/v1/\",\n// prepareHeaders(headers) {\n// headers.set(\"Authorization\", `Bearer ${TokenProvider.getToken()}`);\n// return headers;\n// },\n// }),\n// endpoints: (builder) => ({\n// getCurrentUser: builder.query({\n// query: () => ({\n// url: \"/users/me\",\n// responseHandler: async (response) => {\n// const data = await response.json();\n// lastRenderedProps.Global = {\n// user: data.data.user,\n// };\n// console.log(\"retrieved user\", data.data.user);\n// return data;\n// },\n// }),\n// }),\n// }),\n// });\n\nexport function useGetCurrentUserQuery() {\n return useMemo(() => {\n return {\n isLoading: false,\n data: {\n user: {\n name: \"Test User\",\n },\n },\n };\n }, []);\n}\n","import { useCallback } from \"react\";\nimport { useJSXContext } from \"../../edit-mode/jsx-wrapper.js\";\nimport { isEditMode } from \"./is-edit-mode.js\";\nimport rootStore from \"./lib/root-store.js\";\n\ndeclare global {\n // eslint-disable-next-line @typescript-eslint/no-empty-object-type\n interface SuperblocksAPIRegistry {\n // the plugin injects this during dev time\n }\n}\n\ntype RegisteredAPINames = keyof SuperblocksAPIRegistry;\n\n// Helper type to extract API interfaces from registry\ntype ApiInterfaces<Name extends string> =\n Name extends keyof SuperblocksAPIRegistry\n ? SuperblocksAPIRegistry[Name] extends { input: infer I; output: infer O }\n ? { input: I; output: O }\n : { input: Record<string, unknown>; output: any }\n : { input: never; output: never };\n\nexport const getApiPath = (name: RegisteredAPINames) => {\n let apiPath = name as string;\n if (!apiPath.startsWith(\"/apis\")) {\n apiPath = `/apis/${name}/api.yaml`;\n }\n return apiPath;\n};\n\nexport function useApiStateful<\n Name extends RegisteredAPINames,\n Inputs = ApiInterfaces<Name>[\"input\"],\n Response = ApiInterfaces<Name>[\"output\"],\n>(\n name: Name,\n): {\n run: (inputs?: Inputs) => Promise<Response | undefined>;\n cancel: () => Promise<void>;\n} {\n const { sourceId } = useJSXContext();\n\n const run = useCallback(\n async (inputs?: Inputs): Promise<Response | undefined> => {\n const apiPath = getApiPath(name);\n\n const editMode = isEditMode();\n\n const result = await rootStore.apis.runApiByPath({\n path: apiPath,\n inputs: inputs ?? {},\n ...(editMode ? { injectedCallerId: sourceId } : {}),\n });\n\n return result.data as Response;\n },\n [name, sourceId],\n );\n\n const cancel = useCallback(async () => {\n await rootStore.apis.cancelApi(name);\n }, [name]);\n\n return {\n run,\n cancel,\n };\n}\n","import * as Dialog from \"@radix-ui/react-dialog\";\nimport { isEqual } from \"lodash\";\nimport { observer } from \"mobx-react-lite\";\nimport { useEffect, useRef, useState } from \"react\";\nimport styled from \"styled-components\";\nimport {\n ErrorIconContainer,\n StyledClarkIcon,\n ErrorTitle,\n ErrorMessage,\n ErrorDetails,\n ErrorSummary,\n ErrorStack,\n ActionsContainer,\n SecondaryButton,\n} from \"../lib/internal-details/internal-components/common.js\";\nimport { FixWithClarkButton } from \"../lib/internal-details/internal-components/fix-with-clark-button.js\";\nimport { isEditMode } from \"../lib/internal-details/is-edit-mode.js\";\nimport rootStore from \"../lib/internal-details/lib/root-store.js\";\nimport { editorBridge } from \"./superblocks-editor-bridge.js\";\n\n// Global functions injected by the vanilla error overlay\ndeclare global {\n interface Window {\n __SB_MARK_APP_LOADED?: () => void;\n }\n\n // Vite HMR types for import.meta.hot\n interface ImportMeta {\n readonly hot?: {\n on: (event: string, callback: (payload: any) => void) => void;\n };\n }\n}\n\nconst ModalOverlay = styled(Dialog.Overlay)`\n position: fixed;\n inset: 0;\n background: rgba(0, 0, 0, 0.5);\n z-index: 1000;\n animation: fadeIn 0.2s ease-out;\n\n @keyframes fadeIn {\n from {\n opacity: 0;\n }\n to {\n opacity: 1;\n }\n }\n`;\n\nconst ModalContent = styled(Dialog.Content)`\n position: fixed;\n top: 50%;\n left: 50%;\n transform: translate(-50%, -50%);\n background: white;\n border-radius: 8px;\n box-shadow:\n 0 0 1px rgba(0, 0, 0, 0.1),\n 0 20px 25px -5px rgba(0, 0, 0, 0.1),\n 0 10px 10px -5px rgba(0, 0, 0, 0.04);\n max-width: 650px;\n max-height: 80vh;\n width: 90vw;\n padding: 16px;\n overflow-y: auto;\n z-index: 1001;\n animation: slideIn 0.2s ease-out;\n scrollbar-width: thin;\n\n @keyframes slideIn {\n from {\n opacity: 0;\n transform: translate(-50%, -50%) scale(0.95);\n }\n to {\n opacity: 1;\n transform: translate(-50%, -50%) scale(1);\n }\n }\n\n &:focus {\n outline: none;\n }\n`;\n\nconst InnerModalContent = styled.div`\n position: relative;\n padding: 2.5rem;\n`;\n\nconst ModalCloseButtonContainer = styled.div`\n position: sticky;\n top: 0;\n width: 100%;\n display: flex;\n justify-content: flex-end;\n`;\n\nconst ModalCloseButton = styled(Dialog.Close)`\n height: fit-content;\n background: none;\n border: none;\n color: #6c7689;\n cursor: pointer;\n padding: 4px;\n border-radius: 4px;\n transition: background-color 0.2s;\n\n &:hover {\n background-color: #f3f4f6;\n }\n\n &:focus {\n outline: 2px solid #08a4ff;\n outline-offset: 2px;\n }\n`;\n\nconst ErrorNotificationButton = styled.button`\n position: fixed;\n right: 16px;\n bottom: 16px;\n z-index: 1000;\n background: none;\n border: none;\n padding: 0;\n cursor: pointer;\n outline: none;\n`;\n\nconst ErrorNotificationContent = styled.div`\n background: #ef4444;\n color: white;\n padding: 12px 16px;\n border-radius: 6px;\n font-size: 14px;\n font-weight: 500;\n line-height: 1.4;\n max-width: 40rem;\n box-shadow:\n 0 10px 25px -5px rgba(0, 0, 0, 0.1),\n 0 8px 10px -6px rgba(0, 0, 0, 0.1);\n border: 1px solid rgba(255, 255, 255, 0.1);\n backdrop-filter: blur(10px);\n display: flex;\n align-items: center;\n gap: 8px;\n transition: all 0.2s ease;\n\n &:hover {\n transform: translateY(-2px);\n box-shadow:\n 0 20px 25px -5px rgba(0, 0, 0, 0.15),\n 0 10px 10px -5px rgba(0, 0, 0, 0.1);\n }\n`;\n\nconst ErrorText = styled.span`\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n`;\n\nconst ErrorIcon = styled.svg`\n flex-shrink: 0;\n`;\n\nexport type BuildError =\n | {\n errorType: \"import\";\n error: string;\n stack: string;\n importPath: string;\n }\n | {\n errorType: \"general\";\n error: string;\n stack?: string;\n };\n\nexport type BuildErrorModalProps = {\n isOpen: boolean;\n error: BuildError | null;\n onClose: () => void;\n};\n\nexport const BuildErrorNotification = observer(\n function BuildErrorNotification() {\n const [currentError, setCurrentError] = useState<BuildError | null>(null);\n const [isModalOpen, setIsModalOpen] = useState(false);\n const lastBuildError = useRef<BuildError | null>(null);\n\n useEffect(() => {\n // Signal to the vanilla error overlay that React has loaded\n if (typeof window !== \"undefined\" && window.__SB_MARK_APP_LOADED) {\n window.__SB_MARK_APP_LOADED();\n }\n\n // Listen to Vite's error events\n if (import.meta.hot) {\n import.meta.hot.on(\"vite:error\", (payload) => {\n const error = payload?.err || payload;\n const errorMessage = error?.message || String(error);\n\n // Parse error type based on error name or message\n let buildError: BuildError;\n\n // Check for import errors\n if (error?.name === \"ImportError\" || error?.importPath) {\n buildError = {\n errorType: \"import\",\n error: errorMessage,\n stack: error?.stack || \"\",\n importPath: error?.importPath || \"unknown\",\n };\n } else if (errorMessage.includes(\"Failed to resolve import\")) {\n // Fallback for non-custom import errors\n const importMatch = errorMessage.match(\n /Failed to resolve import [\"'](.+?)[\"']/,\n );\n buildError = {\n errorType: \"import\",\n error: errorMessage,\n stack: error?.stack || \"\",\n importPath: importMatch ? importMatch[1] : \"unknown\",\n };\n } else {\n buildError = {\n errorType: \"general\",\n error: errorMessage,\n stack: error?.stack,\n };\n }\n\n setCurrentError(buildError);\n });\n\n // Clear errors on successful updates\n import.meta.hot.on(\"vite:beforeUpdate\", () => {\n setCurrentError(null);\n setIsModalOpen(false);\n });\n\n // Mark build success after a successful HMR update so the loader can hide\n import.meta.hot.on(\"vite:afterUpdate\", () => {\n rootStore.editStore?.ai.markFirstBuildSuccess();\n });\n }\n }, []);\n\n // Auto-open modal when new error appears\n useEffect(() => {\n if (currentError && !isEqual(lastBuildError.current, currentError)) {\n setIsModalOpen(true);\n lastBuildError.current = currentError;\n editorBridge.sendLoadError(currentError.error);\n }\n }, [currentError]);\n\n // Check if AI is currently generating\n const isAIGenerating = rootStore.editStore?.ai.getIsEditing() ?? false;\n\n // During AI generation, don't show any error UI\n if (!currentError || isAIGenerating) {\n return null;\n }\n\n const displayCornerError = !isModalOpen;\n const errorText =\n currentError.errorType === \"import\" ? \"Import Error\" : \"Build Error\";\n\n return (\n <>\n <BuildErrorModal\n isOpen={isModalOpen}\n error={currentError}\n onClose={() => setIsModalOpen(false)}\n />\n {displayCornerError ? (\n <ErrorNotificationButton onClick={() => setIsModalOpen(true)}>\n <ErrorNotificationContent>\n <ErrorIcon\n width=\"16\"\n height=\"16\"\n viewBox=\"0 0 16 16\"\n fill=\"currentColor\"\n >\n <path d=\"M8 1.5a6.5 6.5 0 100 13 6.5 6.5 0 000-13zM0 8a8 8 0 1116 0A8 8 0 010 8z\" />\n <path d=\"M7.002 11a1 1 0 112 0 1 1 0 01-2 0zM7.1 4.995a.905.905 0 111.8 0l-.35 3.507a.552.552 0 01-1.1 0L7.1 4.995z\" />\n </ErrorIcon>\n <ErrorText>{errorText}</ErrorText>\n </ErrorNotificationContent>\n </ErrorNotificationButton>\n ) : null}\n </>\n );\n },\n);\n\nexport function BuildErrorModal({\n isOpen,\n error,\n onClose,\n}: BuildErrorModalProps) {\n if (!error) return null;\n\n const title = error.errorType === \"import\" ? \"Import error\" : \"Build error\";\n const message =\n error.errorType === \"import\" ? (\n <>\n Error importing <code>{error.importPath}</code>\n </>\n ) : (\n \"An error occurred during the build process\"\n );\n\n // Combine error message with stack trace for full details\n const details =\n error.stack && error.stack.trim()\n ? `${error.error}\\n${error.stack}`\n : error.error;\n\n // Create an Error object for FixWithClarkButton\n const errorObj = new Error(error.error);\n errorObj.stack = details || error.error;\n if (error.errorType === \"import\") {\n errorObj.name = \"ImportError\";\n }\n\n return (\n <Dialog.Root open={isOpen} onOpenChange={onClose}>\n <Dialog.Portal>\n <ModalOverlay />\n <ModalContent data-test=\"build-error-modal\">\n <ModalCloseButtonContainer>\n <ModalCloseButton aria-label=\"Close error dialog\">\n <svg\n width=\"16\"\n height=\"16\"\n viewBox=\"0 0 16 16\"\n fill=\"currentColor\"\n >\n <path d=\"M12.8 4.4L11.6 3.2 8 6.8 4.4 3.2 3.2 4.4 6.8 8 3.2 11.6 4.4 12.8 8 9.2 11.6 12.8 12.8 11.6 9.2 8z\" />\n </svg>\n </ModalCloseButton>\n </ModalCloseButtonContainer>\n\n <InnerModalContent>\n <ErrorIconContainer>\n <StyledClarkIcon />\n </ErrorIconContainer>\n\n <Dialog.Title asChild>\n <ErrorTitle>{title}</ErrorTitle>\n </Dialog.Title>\n\n <ErrorMessage data-test=\"build-error-message\">\n {message}\n </ErrorMessage>\n\n <ActionsContainer>\n {isEditMode() && (\n <FixWithClarkButton error={errorObj} onClick={onClose} />\n )}\n <SecondaryButton onClick={() => window.location.reload()}>\n Refresh page\n </SecondaryButton>\n </ActionsContainer>\n\n {details ? (\n <ErrorDetails>\n <ErrorSummary>Full details</ErrorSummary>\n <ErrorStack>{details}</ErrorStack>\n </ErrorDetails>\n ) : error.errorType === \"general\" && error.error ? (\n <ErrorDetails>\n <ErrorSummary>Error details</ErrorSummary>\n <ErrorStack>{error.error}</ErrorStack>\n </ErrorDetails>\n ) : null}\n </InnerModalContent>\n </ModalContent>\n </Dialog.Portal>\n </Dialog.Root>\n );\n}\n","import rootStore from \"../lib/internal-details/lib/root-store.js\";\n\nimport { getEditStore } from \"./get-edit-store.js\";\nimport type {\n CreationContext,\n ParentInfo,\n CreateRequest as EditorTemplateCreateRequest,\n} from \"../lib/internal-details/sb-wrapper.jsx\";\nimport type {\n PropertyInfo,\n SbElement,\n SourceLocation,\n} from \"@superblocksteam/library-shared/types\";\n\nimport type { CreateRequest } from \"@superblocksteam/library-shared/types\";\n\nfunction getParentInfo(parent: SourceLocation): ParentInfo {\n const selectorIds = Array.from(\n getEditStore().runtimeTrackingStore.getSelectorIdsForSourceId(parent.id),\n );\n const parentComponent =\n selectorIds.length > 0\n ? getEditStore().runtimeTrackingStore.getComponent(selectorIds[0])\n : undefined;\n return {\n type: parentComponent?.type,\n };\n}\n\nfunction getComponentBaseProperties(\n componentType: string,\n _parentInfo: ParentInfo,\n editorTemplateCreateRequest?: EditorTemplateCreateRequest<any>,\n) {\n let properties: Record<string, PropertyInfo> = {};\n\n const editorTemplates =\n rootStore.componentRegistry.getEditorTemplates(componentType);\n if (editorTemplates && editorTemplates.length > 1) {\n throw new Error(\n `Multiple editor templates are not supported yet. Found ${editorTemplates.length} for component type: ${componentType}.`,\n );\n }\n\n if (editorTemplateCreateRequest?.properties) {\n properties = {\n ...properties,\n ...(editorTemplateCreateRequest.properties as Record<\n string,\n PropertyInfo\n >),\n };\n }\n\n // TODO(frameworkless): how do we handle dimensions?\n // const safeDimensions = filterSafeStackDimensionProperties({\n // width: width?.value as Dim | undefined,\n // height: height?.value as Dim | undefined,\n // size: size?.value as Dim | undefined | unknown,\n // });\n return {\n properties: {\n ...properties,\n },\n children: editorTemplateCreateRequest?.children ?? [],\n };\n}\n\nfunction getCreateAtParentElement(\n relativeParent: SourceLocation,\n createAt?: \"root\" | \"dropLocation\",\n): { source: SourceLocation } {\n if (createAt === \"root\") {\n const currentSelectors = Array.from(\n getEditStore().runtimeTrackingStore.getSelectorIdsForSourceId(\n relativeParent.id,\n ),\n );\n\n if (currentSelectors.length === 0) {\n throw new Error(`No selector found for parent: ${relativeParent.id}`);\n }\n\n const appSelectorId =\n getEditStore().runtimeTrackingStore.getClosestAncestorByType(\n currentSelectors[0],\n \"App\",\n );\n\n if (!appSelectorId) {\n throw new Error(\n `App component not found for parent: ${relativeParent.id}`,\n );\n }\n\n const appComponent =\n getEditStore().runtimeTrackingStore.getComponent(appSelectorId);\n\n if (!appComponent) {\n throw new Error(`App component not found for selector: ${appSelectorId}`);\n }\n\n return { source: { id: appComponent.sourceId } };\n } else {\n return { source: relativeParent };\n }\n}\n\n// Create components from the Editor\nexport default async function createComponent({\n componentType,\n parent,\n scopeName,\n baseProperties = {},\n skipSecondaryComponentsCreation, // will only create the primary component. Secondary components are usually trigger components (e.g: Button that triggers the modal)\n otherComponentsUpdates,\n}: {\n componentType: string;\n parent: SourceLocation;\n scopeName: string;\n baseProperties?: Record<string, PropertyInfo>;\n skipSecondaryComponentsCreation?: boolean; // e.g. only create modal and not trigger button\n otherComponentsUpdates?: Record<SbElement, Record<string, PropertyInfo>>;\n}): Promise<SbElement | undefined> {\n const parentInfo = getParentInfo(parent);\n\n const editorTemplates =\n rootStore.componentRegistry.getEditorTemplates(componentType);\n if (editorTemplates && editorTemplates.length > 1) {\n throw new Error(\n `Multiple editor templates are not supported yet. Found ${editorTemplates.length} for component type: ${componentType}.`,\n );\n }\n\n const context: CreationContext = {\n parentInfo,\n defaultTagNames: rootStore.componentRegistry.defaultTagNames,\n selfTagName: componentType,\n generateUniqueName: (prefix: string) =>\n `${prefix}-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,\n };\n\n // Creation\n const editorTemplateCreateRequest = editorTemplates?.[0]?.create?.(context);\n\n const primaryEditorTemplateCreateRequest = Array.isArray(\n editorTemplateCreateRequest,\n )\n ? editorTemplateCreateRequest[0]\n : editorTemplateCreateRequest;\n\n if (\n editorTemplateCreateRequest &&\n primaryEditorTemplateCreateRequest?.type !== componentType\n ) {\n throw new Error(\n `When defining a ${Array.isArray(editorTemplateCreateRequest) ? \"multiple\" : \"single\"} component to be created on an EditorTemplate, the type must match with the component being created. got: ${primaryEditorTemplateCreateRequest?.type} when it should have been ${componentType}`,\n );\n }\n\n const editorTemplateCreateRequests = Array.isArray(\n editorTemplateCreateRequest,\n )\n ? editorTemplateCreateRequest\n : [editorTemplateCreateRequest];\n\n const editStore = getEditStore();\n\n function editorTemplateCreateRequestToInternalCreateRequest({\n editorTemplateCreateRequest,\n baseProperties,\n }: {\n editorTemplateCreateRequest?: EditorTemplateCreateRequest<any>;\n baseProperties: Record<string, PropertyInfo>;\n }): CreateRequest {\n const type = editorTemplateCreateRequest?.type ?? componentType;\n\n const { properties: propertiesFromType, children } =\n getComponentBaseProperties(type, parentInfo, editorTemplateCreateRequest);\n\n const properties = {\n ...propertiesFromType,\n ...baseProperties,\n };\n\n const createAtParentElement = getCreateAtParentElement(\n parent,\n editorTemplateCreateRequest?.createAt,\n );\n\n const primaryComponent: CreateRequest = {\n parentElement: createAtParentElement,\n tagName: type,\n properties,\n children,\n scopeName,\n id: editStore.operationManager.generateSourceId(),\n };\n\n return primaryComponent;\n }\n\n const createRequests = editorTemplateCreateRequests.map(\n (editorTemplateCreateRequest, index) =>\n editorTemplateCreateRequestToInternalCreateRequest({\n editorTemplateCreateRequest,\n baseProperties: index === 0 ? baseProperties : {}, // baseProperties are only applied to the primary component\n }),\n );\n\n const hasOtherComponentsUpdates =\n otherComponentsUpdates && Object.keys(otherComponentsUpdates).length > 0;\n\n const hasMultipleCreateComponents =\n editorTemplateCreateRequests.length > 1 && !skipSecondaryComponentsCreation;\n\n const isBatchOperation =\n hasOtherComponentsUpdates || hasMultipleCreateComponents;\n\n if (isBatchOperation) {\n const performOtherComponentsUpdates = (\n otherComponentsUpdates: Record<SbElement, Record<string, PropertyInfo>>,\n ) => {\n Object.entries(otherComponentsUpdates).forEach(([sourceId, updates]) => {\n editStore.operationManager.setWidgetProperties({\n sourceId: sourceId as SbElement,\n properties: updates,\n });\n });\n };\n\n editStore.operationManager.batchUpdate(() => {\n if (skipSecondaryComponentsCreation) {\n editStore.operationManager.createComponent(createRequests[0]);\n } else {\n createRequests.forEach((createRequest) => {\n editStore.operationManager.createComponent(createRequest);\n });\n }\n\n if (hasOtherComponentsUpdates) {\n performOtherComponentsUpdates(otherComponentsUpdates);\n }\n });\n } else {\n editStore.operationManager.createComponent(createRequests[0]);\n }\n\n /**\n * Returns the single id, or the the last component if there are multiple.\n * See EditorTemplate's definition to understand why.\n */\n return createRequests.at(-1)!.id;\n}\n","import { AiContextMode } from \"@superblocksteam/library-shared/types\";\nimport { makeAutoObservable } from \"mobx\";\nimport { editorBridge } from \"../superblocks-editor-bridge.js\";\nimport type RuntimeTrackingStore from \"./runtime-tracking-store.js\";\nimport type {\n RuntimeErrorData,\n SbElement,\n SbSelector,\n} from \"@superblocksteam/library-shared/types\";\n\nexport class AiManager {\n private _isTaggingEnabled = false;\n private _isEditing = false;\n private _editingComponents: SbElement[] = [];\n private _contextMode: AiContextMode = AiContextMode.SILENT;\n private _targetedComponents: SbElement[] = [];\n private _targetedSelectors: SbSelector[] = [];\n private _hasHadSuccessfulBuild = false;\n private _hasEverHadSuccessfulBuild = false;\n\n constructor(private readonly runtimeTrackingStore: RuntimeTrackingStore) {\n makeAutoObservable(this);\n }\n\n getIsTaggingEnabled() {\n return this._isTaggingEnabled;\n }\n\n getIsEditing() {\n return this._isEditing;\n }\n\n getShouldShowLoader() {\n return this._isEditing && !this._hasHadSuccessfulBuild;\n }\n\n setIsTaggingEnabled(isTaggingEnabled: boolean) {\n this._isTaggingEnabled = isTaggingEnabled;\n }\n\n getAiContextMode() {\n return this._contextMode;\n }\n\n shouldToggleComponentInAiContext() {\n return (\n this._isTaggingEnabled && this._contextMode === AiContextMode.AUTO_SELECT\n );\n }\n\n getTargetedComponents() {\n if (this._isTaggingEnabled && this._contextMode !== AiContextMode.SILENT) {\n return this._targetedComponents;\n }\n return [];\n }\n\n getTargetedSelectors() {\n return this._targetedSelectors;\n }\n\n isEditingComponent(id: SbElement) {\n return (\n this._isEditing &&\n this._editingComponents.some((component) => component === id)\n );\n }\n\n isTargetingComponent(id: SbElement) {\n return this._targetedComponents.includes(id);\n }\n\n startEditing() {\n this._isEditing = true;\n const canvasHasRenderableWidgets =\n this.runtimeTrackingStore.hasRenderedNodes();\n\n if (!this._hasEverHadSuccessfulBuild && canvasHasRenderableWidgets) {\n this._hasEverHadSuccessfulBuild = true;\n this._hasHadSuccessfulBuild = true;\n } else {\n this._hasHadSuccessfulBuild = this._hasEverHadSuccessfulBuild;\n }\n\n this.notifyLoaderState();\n }\n\n setEditingComponents(components: SbElement[]) {\n this._editingComponents = components;\n }\n\n finishEditing() {\n this._isEditing = false;\n this._editingComponents = [];\n if (\n !this._hasEverHadSuccessfulBuild &&\n this.runtimeTrackingStore.hasRenderedNodes()\n ) {\n this._hasEverHadSuccessfulBuild = true;\n this._hasHadSuccessfulBuild = true;\n }\n this.notifyLoaderState();\n }\n\n setAiContextMode(\n mode: AiContextMode,\n components?: { id: SbElement; selectorId?: SbSelector }[],\n ) {\n this._contextMode = mode;\n this._targetedComponents =\n components?.map((component) => component.id) ?? [];\n\n if (this._targetedComponents.length > 0) {\n const selectorIds =\n components?.flatMap((component) => {\n if (component.selectorId) {\n return [component.selectorId];\n }\n return Array.from(\n this.runtimeTrackingStore.getSelectorIdsForSourceId(component.id),\n );\n }) ?? [];\n this._targetedSelectors = selectorIds;\n }\n }\n\n addTargetedSelector(selectorId: SbSelector) {\n // when you add a selector, we remove all other selectors for the same source as targets,\n // since visually for the user we only want to show one target\n this.removeAllSharedSelectors(selectorId);\n this._targetedSelectors.push(selectorId);\n }\n\n toggleTargetedSelector(selectorId: SbSelector) {\n if (this._targetedSelectors.includes(selectorId)) {\n this.removeAllSharedSelectors(selectorId);\n } else {\n this.removeAllSharedSelectors(selectorId);\n this._targetedSelectors.push(selectorId);\n }\n }\n\n isTargetedSelector(selectorId: SbSelector) {\n return this._targetedSelectors.includes(selectorId);\n }\n\n /**\n * Returns true if we are targeting a different selector of the same source id, since in some cases we want to keep\n * the same source targeted, but just highlight another selector of it\n */\n isAlternateSourceIdTarget(sourceId: SbElement, selectorId: SbSelector) {\n if (!this.isTargetingComponent(sourceId)) {\n return false;\n }\n\n const allSelectorIds =\n this.runtimeTrackingStore.getSelectorIdsForSourceId(sourceId);\n if (this.isTargetedSelector(selectorId)) {\n return false;\n }\n return allSelectorIds.has(selectorId);\n }\n\n handleRuntimeError(data: RuntimeErrorData) {\n editorBridge.sendRuntimeError(data);\n }\n\n clearRuntimeError(id: string) {\n editorBridge.sendClearRuntimeError(id);\n }\n\n markFirstBuildSuccess() {\n if (this._hasHadSuccessfulBuild) {\n if (!this._hasEverHadSuccessfulBuild) {\n this._hasEverHadSuccessfulBuild = true;\n }\n return;\n }\n\n this._hasHadSuccessfulBuild = true;\n this._hasEverHadSuccessfulBuild = true;\n this.notifyLoaderState();\n }\n\n private notifyLoaderState() {\n editorBridge.sendAiLoaderState?.(this.getShouldShowLoader());\n }\n\n private removeAllSharedSelectors(selectorId: SbSelector) {\n const sourceId = this.runtimeTrackingStore.getSourceId(selectorId);\n if (sourceId) {\n this.removeAllSelectorsForSource(sourceId);\n }\n }\n\n private removeAllSelectorsForSource(sourceId: SbElement) {\n const allSelectorIds =\n this.runtimeTrackingStore.getSelectorIdsForSourceId(sourceId);\n this._targetedSelectors = this._targetedSelectors.filter(\n (selectorId) => !allSelectorIds.has(selectorId),\n );\n }\n}\n","import { makeAutoObservable } from \"mobx\";\n\nexport type ConnectionStatus =\n | \"pre-init\"\n | \"disconnected\"\n | \"connecting\"\n | \"connected\";\n\nclass ConnectionManager {\n connectionStatus: ConnectionStatus = \"pre-init\"; // The status of the connection to the remote dev server\n\n constructor() {\n makeAutoObservable(this);\n }\n\n initializeSocket() {\n this.connectionStatus = \"connecting\";\n }\n\n connect() {\n this.connectionStatus = \"connected\";\n }\n\n disconnect() {\n this.connectionStatus = \"disconnected\";\n }\n}\n\nexport default ConnectionManager;\n","import type { ServerMethods } from \"@superblocksteam/library-shared/types\";\nimport type { ISocketClient } from \"@superblocksteam/shared\";\n\nexport type EditorSocket = ISocketClient<ServerMethods>;\n\nexport class AsyncSocket {\n private socket: EditorSocket | undefined;\n private socketResolvers: ((s: EditorSocket) => void)[] = [];\n\n setSocket(s: EditorSocket) {\n this.socket = s;\n this.socketResolvers.forEach((resolver) => resolver(s));\n this.socketResolvers.length = 0;\n }\n\n clearSocket() {\n this.socket = undefined;\n this.socketResolvers.length = 0;\n }\n\n async waitForSocket(): Promise<EditorSocket> {\n if (this.socket) return this.socket;\n return new Promise((resolve) => this.socketResolvers.push(resolve));\n }\n\n isConnected(): boolean {\n return !!this.socket;\n }\n}\n","import { trace } from \"@opentelemetry/api\";\nimport {\n connectWebSocket,\n createISocketClient,\n ISocketWithClientAuth,\n} from \"@superblocksteam/shared\";\nimport rootStore from \"../lib/internal-details/lib/root-store.js\";\nimport { consoleLogAttributes } from \"../lib/tracing/console-logging.js\";\nimport {\n getContextFromTraceHeaders,\n createIframeSpan,\n} from \"../lib/tracing/context-utils.js\";\nimport { sendNotification } from \"../lib/user-facing/utils/notification.jsx\";\n\nimport { AsyncSocket } from \"./async-socket.js\";\nimport { getEditStore } from \"./get-edit-store.js\";\nimport type {\n ServerMethods,\n LibraryClientMethods,\n} from \"@superblocksteam/library-shared/types\";\nimport type {\n ISocketClient,\n RequestContextBase,\n} from \"@superblocksteam/shared\";\n\nconst PING_INTERVAL_MS = 15_000;\n\ntype OperationApiISocket = ISocketClient<ServerMethods>;\n\nclass OperationAPI {\n private retryAttempts = 0;\n private asyncSocket = new AsyncSocket();\n private isocket: ISocketWithClientAuth<\n LibraryClientMethods,\n ServerMethods,\n RequestContextBase\n > | null = null;\n\n constructor(private readonly serverUrl: string) {}\n\n /**\n * @throws {Error} if the websocket connection can't be initiated after 3 attempts\n */\n async connect({\n peerId,\n userId,\n authorization,\n applicationId,\n traceContext,\n connectionType,\n connectionTarget,\n }: {\n peerId: string;\n userId?: string;\n authorization: string | undefined;\n applicationId: string;\n traceContext?: Record<string, string>;\n connectionType?: \"initial\" | \"reconnect\";\n connectionTarget?: string;\n }) {\n try {\n const result = await connectSocket(this.serverUrl, {\n peerId,\n userId,\n authorization,\n applicationId,\n traceContext,\n connectionType,\n connectionTarget,\n onClose: this.handleSocketClose({\n peerId,\n userId,\n authorization,\n applicationId,\n }),\n });\n if (result?.socket) {\n this.retryAttempts = 0;\n this.asyncSocket.setSocket(result.socket);\n // Store reference to isocket for token updates\n this.isocket = result.isocket;\n } else {\n throw new Error(\"Failed to create socket connection\");\n }\n } catch {\n this.retryAttempts++;\n console.info(\n `App<>Dev box initial connection failed, retrying attempt ${this.retryAttempts}...`,\n );\n // this retry could fail too\n await this.retryConnection({\n peerId,\n userId,\n authorization,\n applicationId,\n });\n }\n }\n\n ensureFilesSynced = async () => {\n try {\n const socket = await this.asyncSocket.waitForSocket();\n await socket.call.editor.ensureFilesSynced();\n } catch (error) {\n console.error(\"Error ensuring files synced\", error);\n }\n };\n\n /**\n * Updates the authorization token for the socket connection.\n * This is called when the token is refreshed in the parent window.\n */\n updateAuthorization(newAuthorization: string | undefined): void {\n if (this.isocket) {\n this.isocket.setAuthorization(newAuthorization);\n console.log(\n \"[internal] [OperationAPI] Updated iframe socket authorization token\",\n );\n } else {\n console.warn(\n \"[internal] [OperationAPI] Cannot update authorization: socket not yet initialized\",\n );\n }\n }\n\n // Happens after initial connection\n private handleSocketClose({\n peerId,\n userId,\n authorization,\n applicationId,\n }: {\n peerId: string;\n userId?: string;\n authorization: string | undefined;\n applicationId: string;\n }) {\n return async (event: CloseEvent) => {\n // Code 1008 is what we use for application ID mismatch\n if (event.code === 1008) {\n sendNotification({\n message: \"Application ID mismatch\",\n description: `You likely switched between multiple tabs. Please refresh the page.`,\n type: \"warning\",\n duration: 10 * 60, // 10 minutes\n });\n rootStore.editStore?.connectionManager.disconnect();\n return; // Don't retry for application ID mismatch\n }\n\n console.info(\n `[internal] [OperationAPI] App<>Dev box Socket closed, retrying attempt ${this.retryAttempts + 1}...`,\n );\n rootStore.editStore?.connectionManager.disconnect();\n\n await this.retryConnection({\n peerId,\n userId,\n authorization,\n applicationId,\n });\n\n if (this.retryAttempts >= 3) {\n this.asyncSocket.clearSocket();\n }\n this.retryAttempts++;\n };\n }\n\n private async retryConnection({\n peerId,\n userId,\n authorization,\n applicationId,\n }: {\n peerId: string;\n userId?: string;\n authorization: string | undefined;\n applicationId: string;\n }) {\n if (this.retryAttempts < 3) {\n await this.connect({ peerId, userId, authorization, applicationId });\n } else {\n console.info(\n `[internal] [OperationAPI] App<>Dev box Socket closed, failed to reconnect after 3 attempts. Throwing error.`,\n );\n throw new Error(\"Failed to reconnect after 3 attempts\");\n }\n }\n}\n\nexport default new OperationAPI(\n typeof window !== \"undefined\" ? window.location.origin : \"\",\n);\n\n// TODO: remove this once we move the heartbeat logic to the WebSocket RPC framework\n/** Returns a function that can be used to stop the heartbeat */\nfunction startSocketHeartbeat(socket: OperationApiISocket) {\n let timeoutId: ReturnType<typeof setTimeout> | undefined;\n let canceled = false;\n (function loop() {\n if (canceled) return;\n timeoutId = setTimeout(async () => {\n try {\n await socket.call.editor.ping();\n console.debug(\"[internal] [OperationAPI] Pinged library socket\");\n } catch (e) {\n console.warn(\"[internal] [OperationAPI] Ping library socket error\", e);\n }\n loop();\n }, PING_INTERVAL_MS);\n })();\n return () => {\n canceled = true;\n clearTimeout(timeoutId);\n };\n}\n\nasync function connectSocket(\n serverUrl: string,\n {\n peerId,\n userId,\n applicationId,\n authorization,\n onClose,\n traceContext,\n connectionType,\n connectionTarget,\n }: {\n peerId: string;\n userId?: string;\n authorization: string | undefined;\n applicationId: string;\n onClose: (event: CloseEvent) => void;\n traceContext?: Record<string, string>;\n connectionType?: \"initial\" | \"reconnect\";\n connectionTarget?: string;\n },\n): Promise<\n | {\n socket: OperationApiISocket;\n isocket: ISocketWithClientAuth<\n LibraryClientMethods,\n ServerMethods,\n RequestContextBase\n >;\n }\n | undefined\n> {\n if (!serverUrl) {\n return undefined;\n }\n\n const wsUrl = new URL(\"/sb-updates\", serverUrl);\n wsUrl.searchParams.set(\"peerId\", peerId);\n if (userId) {\n wsUrl.searchParams.set(\"userId\", userId);\n }\n wsUrl.searchParams.set(\"applicationId\", applicationId);\n\n rootStore.editStore?.connectionManager.initializeSocket();\n\n // Extract parent context from trace headers if provided\n let parentContext;\n if (traceContext) {\n parentContext = getContextFromTraceHeaders(traceContext);\n }\n\n // Create child span for app websocket connection\n const appWebsocketSpan = createIframeSpan(\n \"devServerAppWebSocketConnection\",\n {\n url: wsUrl.toString(),\n connection_source: \"app\",\n connection_type: connectionType || \"initial\",\n connection_target: connectionTarget || \"default\",\n application_id: applicationId,\n },\n parentContext,\n );\n\n const wsStartTime = Date.now();\n console.log(\n \"[internal] [OperationAPI] Dev server connection app websocket starting\",\n consoleLogAttributes({\n url: wsUrl.toString(),\n connectionSource: \"app\",\n connectionType: connectionType || \"initial\",\n connectionTarget: connectionTarget || \"default\",\n }),\n );\n\n try {\n let stopSocketHeartbeat: (() => void) | undefined;\n const ws = await connectWebSocket(wsUrl.toString());\n const isocket = new ISocketWithClientAuth<\n LibraryClientMethods,\n ServerMethods,\n RequestContextBase\n >(\n ws,\n authorization,\n {\n nonVisualEdit: [\n async () => {\n getEditStore().ui.selectWidget(null); // this also sends a postMessage to parent\n },\n ],\n renameRegisteredComponent: [\n async (payload) => {\n // TODO: do we need a better way to track components?\n const { name, oldName } = payload;\n if (oldName) {\n rootStore.componentRegistry.renameComponent(oldName, name);\n }\n },\n ],\n removeRegisteredComponent: [\n async (payload) => {\n // TODO: do we need a better way to track components?\n rootStore.componentRegistry.deleteComponent(payload.name);\n },\n ],\n deleteEntities: [\n async (_payload) => {\n // no-op\n },\n ],\n clientImport: [\n async (payload) => {\n const { importPath } = payload;\n try {\n await import(/* @vite-ignore */ `${importPath}?v=${Date.now()}`);\n return undefined;\n } catch (error) {\n const err = error as Error;\n return {\n message: err.message,\n stack: err.stack,\n name: err.name,\n };\n }\n },\n ],\n },\n [],\n trace.getTracer(\"superblocks-ui-framework\"),\n {\n onClose: (event) => {\n stopSocketHeartbeat?.();\n stopSocketHeartbeat = undefined;\n onClose(event as unknown as CloseEvent);\n console.log(\n \"[internal] [OperationAPI] Dev server connection app websocket closed\",\n consoleLogAttributes({\n connectionSource: \"app\",\n connectionType: connectionType || \"initial\",\n connectionTarget: connectionTarget || \"default\",\n }),\n );\n rootStore.editStore?.connectionManager.disconnect();\n },\n\n timeouts: {\n connectionTimeoutInSeconds: undefined,\n noResponseTimeoutInSeconds: 60,\n },\n },\n );\n const socket = createISocketClient<\n ServerMethods,\n LibraryClientMethods,\n RequestContextBase\n >(isocket);\n\n const wsEndTime = Date.now();\n const wsDuration = wsEndTime - wsStartTime;\n console.log(\n \"[internal] [OperationAPI] Dev server connection app websocket succeeded\",\n consoleLogAttributes({\n connectionSource: \"app\",\n connectionType: connectionType || \"initial\",\n connectionTarget: connectionTarget || \"default\",\n durationMs: wsDuration,\n }),\n );\n\n // Send connection success to parent for metrics recording\n window.parent.postMessage(\n {\n type: \"app-websocket-connected\",\n payload: {\n success: true,\n durationMs: wsDuration,\n },\n },\n \"*\",\n );\n\n // End span on success\n appWebsocketSpan.end();\n\n stopSocketHeartbeat = startSocketHeartbeat(socket);\n rootStore.editStore?.connectionManager.connect();\n return { socket, isocket };\n } catch (error) {\n const wsEndTime = Date.now();\n const wsDuration = wsEndTime - wsStartTime;\n console.error(\n \"[internal] [OperationAPI] Dev server connection app websocket failed\",\n consoleLogAttributes({\n connectionSource: \"app\",\n connectionType: connectionType || \"initial\",\n connectionTarget: connectionTarget || \"default\",\n durationMs: wsDuration,\n error: error instanceof Error ? error.message : String(error),\n }),\n );\n\n // Send connection failure to parent for metrics recording\n window.parent.postMessage(\n {\n type: \"app-websocket-connected\",\n payload: {\n success: false,\n durationMs: wsDuration,\n error: {\n message: error instanceof Error ? error.message : String(error),\n type: error instanceof Error ? error.constructor.name : \"Unknown\",\n stack: error instanceof Error ? error.stack : undefined,\n },\n },\n },\n \"*\",\n );\n\n // End span with error\n if (error instanceof Error) {\n appWebsocketSpan.recordException(error);\n }\n appWebsocketSpan.end();\n\n rootStore.editStore?.connectionManager.disconnect();\n throw error;\n }\n}\n","// https://github.com/microsoft/TypeScript/issues/47663#issuecomment-1519138189\n// this is for superblocksSlice, import immer\n\nimport { generateSourceId } from \"@superblocksteam/library-shared\";\nimport { action, makeAutoObservable } from \"mobx\";\nimport { generateId } from \"../../lib/utils/generate-id.js\";\nimport SourceUpdateApi from \"../source-update-api.js\";\n\nimport { editorBridge } from \"../superblocks-editor-bridge.js\";\nimport type {\n BatchUpdateRequest,\n CreateRequest,\n DeleteRequest,\n EditOperationPayload,\n EditOperations,\n EditOperationType,\n PropertyInfo,\n ReparentRequest,\n SbElement,\n SetPropertiesRequest,\n SetPropertyRequest,\n SourceLocation,\n} from \"@superblocksteam/library-shared/types\";\n\ntype OptimisticOperation<P> = {\n type: keyof EditOperations;\n payload: P;\n id: string;\n callback?: () => void; // called when the operation is cleared by a hot reload\n};\n\nexport type ReparentTransaction = OptimisticOperation<ReparentRequest>;\ntype SetPropertiesTransaction = OptimisticOperation<SetPropertiesRequest>;\ntype SetPropertyTransaction = OptimisticOperation<SetPropertyRequest>;\ntype CreateComponentTransaction = OptimisticOperation<CreateRequest>;\ntype DeleteComponentsTransaction = OptimisticOperation<DeleteRequest>;\n\ntype PendingTransaction =\n | ReparentTransaction\n | SetPropertiesTransaction\n | SetPropertyTransaction\n | CreateComponentTransaction\n | DeleteComponentsTransaction;\n\nclass OperationManager {\n private pendingTransactions: Array<PendingTransaction> = [];\n\n private waitingForBatch: boolean = false;\n private batchOperations: Array<PendingTransaction> = [];\n private batchOperationTransactionId: string | undefined;\n\n visibleSourceIds: string[] = [];\n\n constructor() {\n makeAutoObservable(this);\n }\n\n get allPendingTransactions() {\n return this.pendingTransactions;\n }\n\n get pendingReparentOperations() {\n return this.pendingTransactions.filter(\n (t) => t.type === \"editor:moveComponent\",\n ) as ReparentTransaction[];\n }\n\n get pendingDeleteOperations() {\n return this.pendingTransactions.filter(\n (t) => t.type === \"editor:deleteComponents\",\n ) as DeleteComponentsTransaction[];\n }\n\n get pendingSetPropertiesOperations() {\n return this.pendingTransactions.filter(\n (t) => t.type === \"editor:setProperties\",\n ) as SetPropertiesTransaction[];\n }\n\n get hasPendingOperations() {\n return this.pendingTransactions.length > 0;\n }\n\n get allNames() {\n return [];\n }\n\n @action\n private executeOrAddToBatch(\n operation: Omit<OptimisticOperation<PendingTransaction[\"payload\"]>, \"id\">,\n addTransaction: boolean = true,\n ) {\n const transactionId = this.batchOperationTransactionId ?? generateId();\n\n const payload = this.waitingForBatch\n ? operation.payload\n : {\n ...operation.payload,\n transaction: {\n id: transactionId,\n origin: \"LIBRARY\",\n },\n };\n\n const opWithId = {\n ...operation,\n id: transactionId,\n payload,\n } as PendingTransaction;\n\n if (addTransaction) {\n this.addPendingTransaction(opWithId);\n }\n\n if (this.waitingForBatch) {\n this.batchOperations.push(opWithId);\n } else {\n switch (operation.type) {\n case \"editor:moveComponent\":\n return editorBridge.editOpRequest(\n \"editor:moveComponent\",\n payload as ReparentRequest,\n );\n case \"editor:setProperties\":\n return editorBridge.editOpRequest(\n \"editor:setProperties\",\n payload as SetPropertiesRequest,\n );\n case \"editor:createComponent\":\n return editorBridge.editOpRequest(\n \"editor:createComponent\",\n payload as CreateRequest,\n );\n case \"editor:deleteComponents\":\n return editorBridge.editOpRequest(\n \"editor:deleteComponents\",\n payload as DeleteRequest,\n );\n }\n }\n }\n\n @action\n private addPendingTransaction(transaction: PendingTransaction) {\n // TODO(alex): good luck!\n // if (transaction.type === \"editor:createComponent\") {\n // getEditStore().runtimeTrackingStore.addOptimisticCreateWidget(\n // transaction.payload as CreateRequest,\n // );\n // }\n this.pendingTransactions.push(transaction);\n }\n\n @action\n clearPendingTransactions(transactionIds: string[]) {\n const toClear = new Set(transactionIds);\n const { cleared, remaining } = this.pendingTransactions.reduce(\n (acc, transaction) => {\n if (toClear.has(transaction.id)) {\n acc.cleared.push(transaction);\n } else {\n acc.remaining.push(transaction);\n }\n return acc;\n },\n {\n cleared: [] as PendingTransaction[],\n remaining: [] as PendingTransaction[],\n },\n );\n\n this.pendingTransactions = remaining;\n\n // Execute callbacks for cleared transactions\n cleared.forEach((transaction) => {\n if (transaction.callback) {\n transaction.callback();\n }\n });\n }\n\n @action\n batchUpdate(performOperations: () => void) {\n this.waitingForBatch = true;\n this.batchOperationTransactionId = generateId();\n performOperations();\n\n editorBridge.editOpRequest(\"editor:batchUpdate\", {\n updates: this.batchOperations.map(\n (op) =>\n ({\n type: op.type,\n payload: op.payload,\n }) as BatchUpdateRequest[\"updates\"][number],\n ),\n transaction: {\n origin: \"LIBRARY\",\n id: this.batchOperationTransactionId,\n },\n });\n\n this.waitingForBatch = false;\n this.batchOperations = [];\n this.batchOperationTransactionId = undefined;\n }\n\n @action\n createComponent(payload: CreateRequest) {\n this.executeOrAddToBatch({\n type: \"editor:createComponent\",\n payload,\n });\n }\n\n @action\n dropComponent(action: {\n from: { source: SourceLocation };\n to: { source: SourceLocation };\n propsToChange?: Record<string, PropertyInfo>;\n }) {\n const { from, to, propsToChange } = action;\n\n const payload: ReparentRequest = {\n from,\n to,\n changedProps: propsToChange ?? {},\n };\n this.executeOrAddToBatch({\n type: \"editor:moveComponent\",\n payload,\n });\n }\n\n @action\n deleteComponents(sourceIds: SbElement[]) {\n const payload: DeleteRequest = {\n elements: sourceIds.map((sourceId) => ({\n source: { id: sourceId },\n })),\n };\n\n this.executeOrAddToBatch(\n {\n type: \"editor:deleteComponents\",\n payload,\n },\n // TODO(alex): not sure if we need this boolean?\n false,\n );\n }\n\n acknowledgeEditOperation(operation: EditOperationPayload<EditOperationType>) {\n if (\n !(\"transaction\" in operation.payload) ||\n !operation.payload.transaction?.id\n ) {\n console.error(\"No transaction id in edit operation\", operation);\n return;\n }\n\n const addOperation = (\n operation: EditOperationPayload<EditOperationType>,\n batchTransactionId?: string,\n ) => {\n switch (operation.type) {\n case \"editor:createComponent\": {\n const { type, payload } =\n operation as EditOperationPayload<\"editor:createComponent\">;\n this.addPendingTransaction({\n type,\n id: batchTransactionId ?? payload.transaction!.id,\n payload,\n });\n break;\n }\n case \"editor:deleteComponents\": {\n const { type, payload } =\n operation as EditOperationPayload<\"editor:deleteComponents\">;\n this.addPendingTransaction({\n type,\n id: batchTransactionId ?? payload.transaction!.id,\n payload,\n });\n break;\n }\n case \"editor:moveComponent\": {\n const { type, payload } =\n operation as EditOperationPayload<\"editor:moveComponent\">;\n this.addPendingTransaction({\n type,\n id: batchTransactionId ?? payload.transaction!.id,\n payload,\n });\n break;\n }\n case \"editor:setProperties\": {\n const { type, payload } =\n operation as EditOperationPayload<\"editor:setProperties\">;\n this.addPendingTransaction({\n type,\n id: payload.transaction!.id,\n payload,\n });\n break;\n }\n case \"editor:deleteProperties\": {\n const { payload } =\n operation as EditOperationPayload<\"editor:deleteProperties\">;\n // we can write the deleteProperties as a setProperties\n const asSetProperties: SetPropertiesRequest = {\n element: {\n source: {\n id: payload.element.source.id,\n },\n },\n properties: Object.fromEntries(\n payload.properties.map((p) => [\n p,\n {\n type: \"STATIC\",\n value: undefined,\n __info: true,\n },\n ]),\n ),\n };\n this.addPendingTransaction({\n type: \"editor:setProperties\",\n id: batchTransactionId ?? payload.transaction!.id,\n payload: asSetProperties,\n });\n break;\n }\n default:\n console.error(\"Unknown edit operation\", operation);\n }\n };\n\n if (operation.type === \"editor:batchUpdate\") {\n const { payload } =\n operation as EditOperationPayload<\"editor:batchUpdate\">;\n if (!payload.transaction?.id) {\n console.error(\"No transaction id in batch\", operation);\n return;\n }\n for (const update of payload.updates) {\n addOperation(update, payload.transaction.id);\n }\n } else {\n addOperation(operation);\n }\n }\n\n @action\n writeRuntimeProperties(\n sourceId: SbElement,\n transactionId: string,\n updates: Record<string, PropertyInfo<unknown>>,\n ) {\n // this can't be part of batch because it came from the editor\n this.addPendingTransaction({\n type: \"editor:setProperties\",\n id: transactionId,\n payload: { element: { source: { id: sourceId } }, properties: updates },\n });\n }\n\n @action\n setWidgetProperties({\n sourceId,\n properties,\n callback,\n }: {\n sourceId: SbElement;\n properties: Record<string, PropertyInfo<unknown>>;\n callback?: () => void;\n }) {\n const payload: SetPropertiesRequest = {\n element: {\n source: {\n id: sourceId,\n },\n },\n properties,\n };\n\n this.executeOrAddToBatch({\n type: \"editor:setProperties\",\n payload,\n callback,\n });\n }\n\n @action\n setWidgetProperty({\n sourceId,\n property,\n value,\n callback,\n }: {\n sourceId: SbElement;\n property: string;\n value: PropertyInfo<unknown>;\n callback?: () => void;\n }) {\n this.setWidgetProperties({\n sourceId,\n properties: { [property]: value },\n callback,\n });\n }\n\n async ensureFilesSynced() {\n await SourceUpdateApi.ensureFilesSynced();\n }\n\n generateSourceId() {\n return generateSourceId();\n }\n}\n\nexport default OperationManager;\n","import {\n ViteMessageKind,\n type PropertyInfo,\n type SbElement,\n} from \"@superblocksteam/library-shared/types\";\nimport { autorun, makeAutoObservable } from \"mobx\";\nimport { createPropertiesPanelDefinition } from \"../../lib/user-facing/properties-panel/properties-panel-definition.js\";\nimport { editorBridge } from \"../superblocks-editor-bridge.js\";\nimport type { ComponentRegistry } from \"../../lib/internal-details/lib/features/component-registry.js\";\nimport type {\n Prop,\n PropertiesDefinition,\n} from \"../../lib/user-facing/properties-panel/props-builder.js\";\nimport type { EditStore } from \"../edit-store.js\";\nimport type { PropertiesPanelDefinition } from \"@superblocksteam/library-shared/props\";\nimport type { SbSelector } from \"@superblocksteam/library-shared/types\";\nimport type { IReactionDisposer } from \"mobx\";\n\nclass PropertiesPanelManager {\n private propertiesDefinitions = new Map<string, PropertiesDefinition>();\n private propertiesPanelTrackerDisposer: IReactionDisposer | null = null;\n\n private _propertyLookupCache = new Map<\n string,\n Record<string, Prop<any, any>>\n >();\n\n private removeHotReloadListener: (() => void) | null = null;\n\n constructor(\n readonly editStore: EditStore,\n readonly componentsManager: ComponentRegistry,\n ) {\n makeAutoObservable<PropertiesPanelManager, \"_propertyLookupCache\">(this, {\n _propertyLookupCache: false,\n });\n\n this.attachHotReloadListener();\n }\n\n getPropertiesPanel(selectorId: SbSelector): PropertiesPanelDefinition {\n const component =\n this.editStore.runtimeTrackingStore.getComponent(selectorId);\n const props = component?.props;\n\n if (!component?.type) {\n return { sections: [] };\n }\n\n const componentType = component.displayName || component.type;\n\n if (!componentType) {\n return { sections: [] };\n }\n\n const propertiesDefinition = this.propertiesDefinitions.get(componentType);\n if (!propertiesDefinition) {\n return { sections: [] };\n }\n\n return createPropertiesPanelDefinition(propertiesDefinition, props ?? {});\n }\n\n trackPropertiesPanel(selectorId: SbSelector) {\n if (this.propertiesPanelTrackerDisposer) {\n this.propertiesPanelTrackerDisposer();\n }\n const sourceId =\n this.editStore.runtimeTrackingStore.getSourceId(selectorId);\n if (!sourceId) {\n return;\n }\n this.propertiesPanelTrackerDisposer = autorun(\n () => {\n const propertiesPanel = this.getPropertiesPanel(selectorId);\n editorBridge.addPropertiesPanel(sourceId, propertiesPanel);\n },\n {\n name: `trackPropertiesPanel[${selectorId}]`,\n },\n );\n }\n\n untrackPropertiesPanel() {\n this.propertiesPanelTrackerDisposer?.();\n this.propertiesPanelTrackerDisposer = null;\n }\n\n getPropertiesDefinition(type: string): PropertiesDefinition | undefined {\n return this.propertiesDefinitions.get(type);\n }\n\n setPropertiesDefinition(\n widgetType: string,\n propertiesDefinition: PropertiesDefinition,\n ) {\n this.propertiesDefinitions.set(widgetType, propertiesDefinition);\n }\n\n updatePropertiesDefinitionForType(type: string) {\n // No-op: Hot reload triggers re-registration which calls setPropertiesDefinition\n // This method is kept for backward compatibility with hot reload messages\n console.log(\"[internal] [NOOP] updatePropertiesDefinitionForType: \", type);\n }\n\n computeAndApplySideEffectsForPropertyUpdate(payload: {\n sourceId: SbElement;\n updates: Record<string, PropertyInfo<unknown>>;\n }): Record<SbElement, Record<string, PropertyInfo<unknown>>> {\n console.log(\n \"[internal] [NOOP] computeAndApplySideEffectsForPropertyUpdate\",\n );\n return {\n [payload.sourceId]: payload.updates,\n };\n }\n\n /**\n * When a custom component's source code is updated, we want to update the properties definition for that component.\n * In order to do that, we need to listen to vite's hot reload events. We can't put import.meta.hot calls in the library\n * because Vite just compiled all of those out in library builds, so we inject a listener from the plugin instead.\n * https://github.com/vitejs/vite/blob/v6.2/packages/vite/src/node/plugins/define.ts#L37\n */\n private attachHotReloadListener() {\n this.removeHotReloadListener?.();\n\n this.removeHotReloadListener = this.editStore.onViteMessage(\n ViteMessageKind.UPDATE_CUSTOM_COMPONENT,\n (message) => {\n this.updatePropertiesDefinitionForType(message.component);\n },\n );\n }\n}\n\nexport default PropertiesPanelManager;\n","/* eslint-disable @typescript-eslint/no-unsafe-declaration-merging */\nimport { Graph } from \"@dagrejs/graphlib\";\nimport { action, makeObservable, observable } from \"mobx\";\nimport type { Edge, GraphOptions } from \"@dagrejs/graphlib\";\n\n// Generic type parameters are used in the interface below via declaration merging\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport class ObservableGraph<NL = any, EL = any> extends Graph {\n constructor(args: GraphOptions) {\n super(args);\n\n makeObservable<any>(this, {\n // Core graph properties\n _label: observable,\n _defaultNodeLabelFn: observable,\n _defaultEdgeLabelFn: observable,\n\n // Node storage\n _nodes: observable,\n _nodeCount: observable,\n\n // Edge storage\n _in: observable,\n _preds: observable,\n _out: observable,\n _sucs: observable,\n _edgeObjs: observable,\n _edgeLabels: observable,\n _edgeCount: observable,\n\n // Compound graph properties (conditionally set)\n ...(args.compound\n ? {\n _parent: observable,\n _children: observable,\n }\n : {}),\n\n // Mutation methods (actions)\n setGraph: action,\n setDefaultNodeLabel: action,\n setNode: action,\n setNodes: action,\n removeNode: action,\n setParent: action,\n setDefaultEdgeLabel: action,\n setEdge: action,\n setPath: action,\n removeEdge: action,\n });\n }\n}\n\n// Use interface declaration merging to add type-safe method signatures\nexport interface ObservableGraph<NL = any, EL = any> {\n // Node operations\n setNode(name: string, label?: NL): this;\n node(name: string): NL;\n setDefaultNodeLabel(label: NL): this;\n setDefaultNodeLabel(labelFn: (v: string) => NL): this;\n\n // Edge operations\n setEdge(v: string, w: string, label?: EL, name?: string): this;\n setEdge(edge: Edge, label?: EL): this;\n edge(v: string, w: string, name?: string): EL;\n edge(edge: Edge): EL;\n setDefaultEdgeLabel(label: EL): this;\n setDefaultEdgeLabel(\n labelFn: (v: string, w: string, name?: string) => EL,\n ): this;\n setPath(vs: string[], label?: EL): this;\n}\n","import { SELECTOR_ID_ATTRIBUTE } from \"@superblocksteam/library-shared\";\nimport { makeAutoObservable, observable } from \"mobx\";\nimport type { ComponentNode, ITrackingStore } from \"./types\";\nimport type {\n SbElement,\n SbSelector,\n} from \"@superblocksteam/library-shared/types\";\n\nexport class RuntimeComponentNode implements ComponentNode {\n private readonly store: ITrackingStore;\n public readonly selectorId: SbSelector;\n public readonly sourceId: SbElement;\n public readonly type: any;\n public readonly isSbComponent: boolean;\n public readonly isHtmlElement: boolean;\n public readonly noSelect?: boolean;\n\n public props?: Record<string, unknown>;\n constructor(\n store: ITrackingStore,\n params: {\n selectorId: SbSelector;\n sourceId: SbElement;\n type: any;\n isSbComponent: boolean;\n isHtmlElement: boolean;\n noSelect?: boolean;\n },\n ) {\n this.store = store;\n this.sourceId = params.sourceId;\n this.selectorId = params.selectorId;\n this.type = params.type;\n this.isSbComponent = params.isSbComponent;\n this.isHtmlElement = params.isHtmlElement;\n this.noSelect = params.noSelect;\n makeAutoObservable<RuntimeComponentNode>(this, {\n type: observable.ref,\n props: observable.ref,\n });\n }\n\n get firstRenderedTag() {\n if (this?.isHtmlElement) {\n return this.selectorId;\n }\n\n const element = document.querySelector(\n `[${SELECTOR_ID_ATTRIBUTE}=\"${this.selectorId}\"]`,\n );\n if (element) {\n return this.selectorId;\n }\n\n const children = this.store.graph.children(this.selectorId) ?? [];\n for (const child of children) {\n const childComponent = this.store.jsxNodes[child as SbSelector];\n const result = childComponent?.firstRenderedTag;\n if (result) {\n return result;\n }\n }\n return undefined;\n }\n\n get nearestSelectableAncestor() {\n // valid situations where I am the nearest registered ancestor:\n // - I am a registered REACT component (not an html element)\n // - I am a registered html element and I have no data-no-select attribute\n if (this.isSbComponent && !this.noSelect) {\n return this.selectorId;\n }\n const componentParent = this.store.graph.parent(this.selectorId) as\n | SbSelector\n | undefined;\n if (componentParent) {\n return this.store.jsxNodes[componentParent]?.nearestSelectableAncestor;\n }\n return undefined;\n }\n\n get displayName() {\n if (this.isHtmlElement) {\n return this.type;\n }\n\n return getTypeString(this.type);\n }\n}\n\nfunction getTypeString(type: any) {\n if (typeof type === \"string\") {\n return type;\n }\n return type.displayName || type.name || \"Component\";\n}\n","import { makeAutoObservable } from \"mobx\";\nimport { ObservableGraph } from \"../runtime-graph/observable-graph.js\";\nimport { RuntimeComponentNode } from \"../runtime-graph/runtime-component-node.js\";\nimport type { EditStore } from \"../edit-store.js\";\nimport type {\n NodeLabel,\n EdgeType,\n ComponentNode,\n SourceCodeNode,\n} from \"../runtime-graph/types.js\";\nimport type {\n SbElement,\n SbSelector,\n} from \"@superblocksteam/library-shared/types\";\n\nclass RuntimeTrackingStore {\n // Is reference to edit store needed?\n constructor(readonly editStore: EditStore | undefined) {\n makeAutoObservable<RuntimeTrackingStore>(this);\n }\n\n private graph = new ObservableGraph<NodeLabel, EdgeType>({\n directed: true,\n multigraph: true,\n compound: true,\n });\n\n // Store component metadata separately from graph nodes\n private jsxNodes: Partial<Record<SbSelector, ComponentNode>> = {};\n private sourceNodes: Partial<Record<SbElement, SourceCodeNode>> = {};\n\n private disabledComponents = new Set<SbSelector>();\n\n public registerComponent(\n selectorId: SbSelector,\n params: {\n sourceId: SbElement;\n type: any;\n parentSelectorId?: SbSelector;\n isSbComponent: boolean;\n isHtmlElement: boolean;\n noSelect?: boolean;\n },\n ) {\n // jsx metadata\n const componentNode = new RuntimeComponentNode(\n {\n jsxNodes: this.jsxNodes,\n graph: this.graph,\n },\n {\n selectorId,\n sourceId: params.sourceId,\n type: params.type,\n isSbComponent: params.isSbComponent,\n isHtmlElement: params.isHtmlElement,\n noSelect: params.noSelect,\n },\n );\n this.jsxNodes[selectorId] = componentNode;\n\n this.graph.setNode(selectorId, {\n id: selectorId,\n type: \"JSX\",\n } satisfies NodeLabel);\n\n // Set parent-child relationship using compound graph\n if (params.parentSelectorId) {\n if (!this.graph.hasNode(params.parentSelectorId)) {\n this.graph.setNode(params.parentSelectorId, {\n id: params.parentSelectorId,\n type: \"JSX\",\n } satisfies NodeLabel);\n }\n this.graph.setParent(selectorId, params.parentSelectorId);\n }\n\n // source metadata\n const sourceNode: SourceCodeNode = {\n sourceId: params.sourceId,\n };\n this.sourceNodes[params.sourceId] = sourceNode;\n this.graph.setNode(params.sourceId, {\n id: params.sourceId,\n type: \"SOURCE\",\n } satisfies NodeLabel);\n\n // connect jsx node to source node\n this.graph.setEdge(params.sourceId, selectorId, undefined, \"SOURCE_TO_JSX\");\n }\n\n public getDisplayName(selectorId: SbSelector) {\n return this.jsxNodes[selectorId]?.displayName ?? \"Component\";\n }\n\n public unregisterComponent(selectorId: SbSelector) {\n this.graph.removeNode(selectorId);\n\n // allow these to be GC'd\n delete this.jsxNodes[selectorId];\n\n this.disabledComponents.delete(selectorId);\n }\n\n public getFirstAnchorableTag(selectorId: SbSelector): SbSelector | undefined {\n const firstRenderedTag = this.jsxNodes[selectorId]?.firstRenderedTag;\n return firstRenderedTag;\n }\n\n public getNearestSelectableAncestor(\n selectorId: SbSelector,\n skipSelf: boolean = false,\n ): SbSelector | undefined {\n if (skipSelf) {\n const componentParent = this.graph.parent(selectorId) as\n | SbSelector\n | undefined;\n if (componentParent) {\n return this.jsxNodes[componentParent]?.nearestSelectableAncestor;\n }\n return undefined;\n }\n return this.jsxNodes[selectorId]?.nearestSelectableAncestor;\n }\n\n public updatePropsForComponent(\n selectorId: SbSelector,\n props: Record<string, unknown>,\n ) {\n const componentNode = this.jsxNodes[selectorId];\n if (componentNode) {\n componentNode.props = props;\n\n if (props.disabled) {\n this.disabledComponents.add(selectorId);\n } else {\n this.disabledComponents.delete(selectorId);\n }\n }\n }\n\n public getComponent(selectorId: SbSelector) {\n return this.jsxNodes[selectorId];\n }\n\n public getComponentParent(selectorId: SbSelector): SbSelector {\n return this.graph.parent(selectorId) as SbSelector;\n }\n\n public getComponentChildren(selectorId: SbSelector): SbSelector[] {\n return (this.graph.children(selectorId) as SbSelector[]) || [];\n }\n\n public getSelectorIdsForSourceId(sourceId: SbElement): Set<SbSelector> {\n const sourceNode = this.sourceNodes[sourceId];\n if (!sourceNode) {\n return new Set();\n }\n const sourceNodeEdges = this.graph.outEdges(sourceId) ?? [];\n return new Set(\n sourceNodeEdges\n .filter((edge) => {\n return edge.name === \"SOURCE_TO_JSX\";\n })\n .map((edge) => edge.w as SbSelector),\n );\n }\n\n public getSourceId(selectorId: SbSelector): SbElement | undefined {\n return this.jsxNodes[selectorId]?.sourceId;\n }\n\n public getClosestAncestorByType(\n selectorId: SbSelector,\n type: string,\n ): SbSelector | undefined {\n let current: SbSelector | undefined = selectorId;\n while (current) {\n const component = this.jsxNodes[current];\n if (component?.type === type) return current;\n current = this.graph.parent(current) as SbSelector | undefined;\n }\n return undefined;\n }\n\n public hasRenderedNodes(): boolean {\n return Object.keys(this.jsxNodes).length > 0;\n }\n\n public getDisabledComponents(): SbSelector[] {\n return Array.from(this.disabledComponents);\n }\n\n /**\n * Given a selectorId that represents a DOM element, walks up the component tree\n * to find the outermost registered component whose firstRenderedTag matches this selectorId.\n * This is used to select the component when clicking on its root DOM element.\n *\n * IMPORTANT: This only returns a component if the anchorSelectorId is the IMMEDIATE parent\n * of the component (i.e., the component doesn't have any intermediate nodes between itself\n * and the anchor). This prevents inner HTML elements from being treated as component roots.\n *\n * ONLY returns registered components (isSbComponent: true). Unregistered wrapper components\n * are treated as transparent and skipped.\n *\n * Returns undefined if no registered component has this as its firstRenderedTag.\n */\n public getOutermostComponentForFirstRenderedTag(\n anchorSelectorId: SbSelector,\n ): SbSelector | undefined {\n // First check: is the anchor itself a registered component?\n const anchorComponent = this.jsxNodes[anchorSelectorId];\n if (\n anchorComponent &&\n !anchorComponent.isHtmlElement &&\n anchorComponent.isSbComponent\n ) {\n // The clicked element itself is a registered component\n return anchorSelectorId;\n }\n\n // Second check: walk up to find registered components whose DIRECT firstRenderedTag\n // is this anchor (meaning there are no intermediate HTML elements)\n // ONLY collect registered components (isSbComponent: true)\n const registeredMatches: SbSelector[] = [];\n let current: SbSelector | undefined = this.graph.parent(\n anchorSelectorId,\n ) as SbSelector | undefined;\n\n while (current) {\n const component = this.jsxNodes[current];\n if (!component) {\n break;\n }\n\n // Check if this is a REGISTERED component (not an HTML element, and isSbComponent is true)\n // whose firstRenderedTag directly matches our anchor\n if (\n !component.isHtmlElement &&\n component.isSbComponent &&\n component.firstRenderedTag === anchorSelectorId\n ) {\n registeredMatches.push(current);\n }\n\n // Walk up to parent\n current = this.graph.parent(current) as SbSelector | undefined;\n }\n\n // Return the outermost registered component, or undefined if none found\n return registeredMatches.length > 0\n ? registeredMatches[registeredMatches.length - 1]\n : undefined;\n }\n}\n\nexport default RuntimeTrackingStore;\n","import { Property, Dim } from \"@superblocksteam/library-shared\";\nimport { makeAutoObservable } from \"mobx\";\nimport { startEditorSync } from \"../mobx-sync/mobx-editor-sync.js\";\nimport type { RootStore } from \"../../lib/internal-details/lib/root-store.js\";\nimport type { PropertyInfo } from \"@superblocksteam/library-shared\";\nimport type {\n SbElement,\n SbSelector,\n} from \"@superblocksteam/library-shared/types\";\n\ntype ResizeState = {\n selectorId: SbSelector;\n sourceId: SbElement;\n dragStartX: number;\n dragStartY: number;\n start: {\n width: number;\n height: number;\n };\n resizedPosition: string;\n widthToUpdate: Dim | null;\n heightToUpdate: Dim | null;\n isApplyingResize: boolean;\n};\n\nexport class ResizingManager {\n private _activeResizes: Map<SbElement, ResizeState> = new Map();\n\n constructor(private root: RootStore) {\n makeAutoObservable(this);\n\n startEditorSync({\n store: this,\n storeId: \"resizing\",\n projection(store) {\n const resize = store.activeResize;\n return {\n isResizing: resize != null,\n activeResize: resize\n ? {\n width: resize.widthToUpdate,\n height: resize.heightToUpdate,\n }\n : null,\n };\n },\n });\n }\n\n get activeResize() {\n const selectedSourceId = this.root.editStore?.ui.getSelectedSourceIds()[0];\n if (!selectedSourceId) {\n return null;\n }\n return this._activeResizes.get(selectedSourceId);\n }\n\n private isLockedAspectRatio(selectorId: SbSelector) {\n const component =\n this.root.editStore?.runtimeTrackingStore.getComponent(selectorId);\n\n const editorConfig = component?.type\n ? this.root.componentRegistry.getEditorConfig(component?.type)\n : null;\n return editorConfig?.isFixedAspectRatio === true;\n }\n\n public startResizing(\n dragStartX: number,\n dragStartY: number,\n selectorId: SbSelector,\n position: string,\n ) {\n const component =\n this.root.editStore?.runtimeTrackingStore.getComponent(selectorId);\n if (!component) {\n console.error(`Could not find component ${selectorId}`);\n return;\n }\n\n this._activeResizes.set(component.sourceId, {\n selectorId,\n sourceId: component.sourceId,\n dragStartX,\n dragStartY,\n start: {\n width:\n (component?.props?.width as Dim)?.value ??\n (component?.props?.size as Dim)?.value ??\n 0,\n height: (component?.props?.height as Dim)?.value ?? 0,\n },\n resizedPosition: position,\n widthToUpdate: null,\n heightToUpdate: null,\n isApplyingResize: false,\n });\n }\n\n private calculateDimension(baseValue: number, delta: number): number {\n return Math.floor(Math.max(baseValue + delta, 0));\n }\n\n private handleResizeDimension(params: {\n resizeState: ResizeState;\n dimension: \"width\" | \"height\";\n delta: number;\n canResize: boolean;\n mode: string;\n position: string;\n }) {\n const { resizeState, dimension, delta, canResize, position } = params;\n if (!canResize) return;\n\n const isHorizontal = dimension === \"width\";\n const startValue = resizeState.start[dimension];\n\n let newValue = null;\n\n if (position.includes(isHorizontal ? \"left\" : \"top\")) {\n newValue = this.calculateDimension(startValue, -delta);\n } else if (position.includes(isHorizontal ? \"right\" : \"bottom\")) {\n newValue = this.calculateDimension(startValue, delta);\n }\n\n return () => {\n if (newValue) {\n resizeState[`${dimension}ToUpdate`] = Dim.px(newValue);\n }\n };\n }\n\n public resizeWidget(\n currentX: number,\n currentY: number,\n selectorId: SbSelector,\n canResizeWidth: boolean,\n canResizeHeight: boolean,\n ) {\n const sourceId =\n this.root.editStore?.runtimeTrackingStore.getSourceId(selectorId);\n const component =\n this.root.editStore?.runtimeTrackingStore.getComponent(selectorId);\n const type = component?.type;\n if (!type) {\n return;\n }\n const resizeState = sourceId && this._activeResizes.get(sourceId);\n if (!resizeState) {\n return;\n }\n const widthMode = (component?.props?.width as Dim)?.mode;\n const heightMode = (component?.props?.height as Dim)?.mode;\n const lockedAspectRatio = this.isLockedAspectRatio(selectorId);\n\n const deltaX = currentX - resizeState.dragStartX;\n const deltaY = lockedAspectRatio\n ? deltaX\n : currentY - resizeState.dragStartY;\n\n const updateWidth = this.handleResizeDimension({\n resizeState,\n dimension: \"width\",\n delta: deltaX,\n canResize: canResizeWidth,\n mode: widthMode,\n position: resizeState.resizedPosition,\n });\n\n const updateHeight = this.handleResizeDimension({\n resizeState,\n dimension: \"height\",\n delta: deltaY,\n canResize: canResizeHeight,\n mode: heightMode,\n position: resizeState.resizedPosition,\n });\n\n if (updateWidth) {\n updateWidth();\n }\n if (updateHeight) {\n updateHeight();\n }\n\n this._activeResizes.set(sourceId, resizeState);\n }\n\n // sourceId rather than instance because we are resizing all items of this source at the same time.\n public pendingResize(sourceId: SbElement) {\n const resizeState = this._activeResizes.get(sourceId);\n if (!resizeState) {\n return null;\n }\n return {\n width: resizeState.widthToUpdate,\n height: resizeState.heightToUpdate,\n };\n }\n\n public get hasAnyPendingResize() {\n return Array.from(this._activeResizes.values()).some(\n // Margins are not here because they are not part of the actual resizing, they are just to improve the UX with the positioning\n (state) => state.widthToUpdate || state.heightToUpdate,\n );\n }\n\n public get pendingResizes() {\n return Array.from(this._activeResizes.values()).filter(\n (state) => !state.isApplyingResize,\n );\n }\n\n public applyResize(selectorId: SbSelector) {\n const sourceId =\n this.root.editStore?.runtimeTrackingStore.getSourceId(selectorId);\n const component =\n this.root.editStore?.runtimeTrackingStore.getComponent(selectorId);\n const type = component?.type;\n if (!type) {\n return;\n }\n const resizeState = sourceId && this._activeResizes.get(sourceId);\n if (!resizeState) {\n return;\n }\n\n resizeState.isApplyingResize = true;\n\n const properties: Record<string, PropertyInfo<unknown>> = {\n ...(resizeState.heightToUpdate &&\n type !== \"Icon\" && {\n height: Property.Dimension(resizeState.heightToUpdate),\n }),\n ...(resizeState.widthToUpdate &&\n type !== \"Icon\" && {\n width: Property.Dimension(resizeState.widthToUpdate),\n }),\n ...(resizeState.widthToUpdate &&\n type === \"Icon\" && {\n size: Property.Dimension(resizeState.widthToUpdate),\n }),\n };\n\n if (Object.keys(properties).length > 0) {\n this.root.editStore?.operationManager.setWidgetProperties({\n sourceId: resizeState.sourceId,\n properties,\n callback: () => {\n this._activeResizes.delete(sourceId);\n },\n });\n }\n }\n}\n","import { action, makeObservable, observable, when } from \"mobx\";\nimport { editorBridge } from \"../superblocks-editor-bridge.js\";\nimport { ResizingManager } from \"./resizing-store.js\";\nimport type { RootStore } from \"../../lib/internal-details/lib/root-store.js\";\nimport type { EditStore } from \"../edit-store.js\";\nimport type {\n SbElement,\n SbSelector,\n} from \"@superblocksteam/library-shared/types\";\n\nconst MULTI_SELECT_ENABLED = false; // TODO https://linear.app/superblocks/issue/FE-1673\n\nclass UIStore {\n resizing: ResizingManager;\n\n // TODO (Alex): audit ALL usage of these 4 to ensure interactions work correctly\n private _selectedSourceIds: SbElement[] = [];\n private _selectedSelectorIds: SbSelector[] = [];\n private _focusedSelectorId: SbSelector | null = null;\n\n private _rootInstanceData: Map<\n SbSelector,\n {\n sourceId: SbElement;\n isRoot: boolean;\n }\n > = new Map();\n\n private newComponentSelectPromise:\n | (Promise<void> & { cancel(): void })\n | null = null;\n\n constructor(\n readonly root: RootStore,\n readonly editStore: EditStore,\n ) {\n this.resizing = new ResizingManager(root);\n\n makeObservable<\n UIStore,\n \"_selectedSourceIds\" | \"_selectedSelectorIds\" | \"_focusedSelectorId\"\n >(this, {\n _selectedSourceIds: observable,\n _selectedSelectorIds: observable,\n _focusedSelectorId: observable,\n\n setSelectedSourceIds: action,\n setSelectedSelectorIds: action,\n setFocusedIds: action,\n selectWidget: action,\n });\n }\n\n /*\n * This is a optimistic way to improve the UX for repeated elements.\n * The IDEAL solution would be that the editor frame knows about selector IDs too. For now, this should work in most cases.\n *\n * This works like returning getSelectorIdsForSourceId except for 1 case.\n * If there is a singularly selected component and there are multiple components that match the given source ID,\n * we should try to find the correct component by seeing if new source ID is an ancestor of the selected component.\n */\n getMostRelevantSelectorIdsForSourceId(sourceId: SbElement): SbSelector[] {\n const selectorIds =\n this.editStore.runtimeTrackingStore.getSelectorIdsForSourceId(sourceId);\n const selectedSelectorIds = this.getSelectedSelectorIds();\n if (selectorIds.size <= 1 || selectedSelectorIds.length !== 1) {\n // tiny optimization - if there's only 1 selectorId that matches the source, then we don't need anything fancy\n // another optimization, if there are MULTIPLE selected selectorIDs, then we should just skip this step in case its too costly\n return Array.from(selectorIds);\n }\n\n const getSelectorIdMatchingSourceIdInAncestry = (\n selId: SbSelector,\n srcId: SbElement,\n maxDepth = 10,\n ): null | SbSelector => {\n if (maxDepth <= 0) {\n return null;\n }\n if (this.editStore.runtimeTrackingStore.getSourceId(selId) === srcId) {\n return selId;\n }\n const parentSelectorId =\n this.editStore.runtimeTrackingStore.getComponentParent(selId);\n if (parentSelectorId) {\n return getSelectorIdMatchingSourceIdInAncestry(\n parentSelectorId,\n srcId,\n maxDepth - 1,\n );\n }\n return null;\n };\n\n const matchingSelectorId = getSelectorIdMatchingSourceIdInAncestry(\n selectedSelectorIds[0],\n sourceId,\n );\n if (matchingSelectorId) {\n return [matchingSelectorId];\n }\n\n return Array.from(selectorIds);\n }\n\n // TODO (Alex): For these getters, we should differentiate between source and instance selection\n isSourceSelected(sourceId: SbElement) {\n if (this._selectedSourceIds.includes(sourceId)) {\n return true;\n }\n const selectorIds =\n this.editStore.runtimeTrackingStore.getSelectorIdsForSourceId(sourceId);\n return (\n selectorIds != null &&\n Array.from(selectorIds).some((selectorId) =>\n this._selectedSelectorIds.includes(selectorId),\n )\n );\n }\n getSelectedSourceIds(): SbElement[] {\n const sourceSet = new Set<SbElement>();\n this._selectedSourceIds.forEach((sourceId) => {\n sourceSet.add(sourceId);\n });\n this._selectedSelectorIds.forEach((selectorId) => {\n const sourceId =\n this.editStore.runtimeTrackingStore.getSourceId(selectorId);\n if (sourceId) {\n sourceSet.add(sourceId);\n }\n });\n return Array.from(sourceSet);\n }\n\n getSelectedSelectorIds(): SbSelector[] {\n return this._selectedSelectorIds;\n }\n\n private get focusedSelectorId(): SbSelector | null {\n return this._focusedSelectorId;\n }\n\n getFocusedSourceId(): SbElement | null {\n if (!this._focusedSelectorId) {\n return null;\n }\n return (\n this.editStore.runtimeTrackingStore.getSourceId(\n this._focusedSelectorId,\n ) ?? null\n );\n }\n getFocusedSelectorId(): SbSelector | null {\n return this.focusedSelectorId;\n }\n // End of getters that need to be eventually improved\n\n setSelectedSourceIds(sourceIds: SbElement[]) {\n this.newComponentSelectPromise?.cancel();\n this.subscribeNewSourceIdsToRuntimeSync(sourceIds);\n this._selectedSourceIds = sourceIds;\n }\n\n private subscribeNewSourceIdsToRuntimeSync(sourceIds: SbElement[]) {\n const previousSourceIds = new Set(this._selectedSourceIds);\n const newSourceIds = new Set(sourceIds);\n\n previousSourceIds.forEach((sourceId) => {\n if (!newSourceIds.has(sourceId)) {\n this.editStore.runtimeSubscriptionsStore.unsubscribe(sourceId);\n }\n });\n\n newSourceIds.forEach((sourceId) => {\n if (!previousSourceIds.has(sourceId)) {\n this.editStore.runtimeSubscriptionsStore.subscribe(sourceId);\n }\n });\n }\n\n setSelectedSelectorIds(selectorIds: SbSelector[]) {\n this.newComponentSelectPromise?.cancel();\n this._selectedSelectorIds = selectorIds;\n }\n\n setFocusedIds(selectorId: SbSelector | null) {\n this._focusedSelectorId = selectorId;\n }\n\n selectWidget(\n selectorId: SbSelector | null,\n _addToSelection: boolean = false,\n ) {\n this.newComponentSelectPromise?.cancel();\n const addToSelection = _addToSelection && MULTI_SELECT_ENABLED;\n\n const component =\n selectorId &&\n this.editStore.runtimeTrackingStore.getComponent(selectorId);\n const sourceId = component?.sourceId;\n\n if (!component || !sourceId) {\n editorBridge.selectWidgets([]);\n this.setSelectedSourceIds([]);\n this.setSelectedSelectorIds([]);\n this.editStore.propertiesPanelManager.untrackPropertiesPanel();\n\n // Unlock design mode when deselecting\n if (this.editStore.interactionMode === \"design\") {\n this.editStore.setDesignModeLocked(false);\n }\n return;\n }\n\n const sourceIds = addToSelection\n ? [...this._selectedSourceIds, sourceId]\n : [sourceId];\n const selectorIds = addToSelection\n ? [...this._selectedSelectorIds, selectorId]\n : [selectorId];\n this.setSelectedSourceIds(sourceIds);\n this.setSelectedSelectorIds(selectorIds);\n\n this.editStore.propertiesPanelManager.trackPropertiesPanel(selectorId);\n\n editorBridge.selectWidgets(sourceIds, selectorId);\n\n // Lock design mode when a widget is selected in design mode\n if (this.editStore.interactionMode === \"design\") {\n this.editStore.setDesignModeLocked(true);\n }\n }\n\n /**\n * This is cursed because component selection actually needs to be done by instance ids, but\n * instance IDs are only guaranteed to be stable after the component is rendered, while source IDs\n * are assigned by the source tracker.\n *\n * If _any_ other selection comes in before we select something, we will cancel this reaction\n */\n async selectNewComponentBySourceId(\n sourceId: SbElement,\n selectorIdsToIgnore = new Set<SbSelector>(),\n ) {\n this.newComponentSelectPromise?.cancel();\n\n // first select the instance id that is already rendered, it will be an optimistic instance id\n this.newComponentSelectPromise = when(() =>\n Array.from(\n this.editStore.runtimeTrackingStore.getSelectorIdsForSourceId(sourceId),\n ).some((selectorId) => !selectorIdsToIgnore.has(selectorId)),\n );\n await this.newComponentSelectPromise;\n\n const selectorId = Array.from(\n this.editStore.runtimeTrackingStore.getSelectorIdsForSourceId(sourceId),\n )[0];\n if (selectorId) {\n this.selectWidget(selectorId);\n }\n }\n}\n\nexport default UIStore;\n","import type { EditStore } from \"../edit-store.js\";\nimport type RuntimeTrackingStore from \"../features/runtime-tracking-store.js\";\nimport type { ComponentNode } from \"../runtime-graph/types.js\";\nimport type {\n RuntimeSyncComposite,\n RuntimeSyncComponentData,\n RuntimeSyncComponentMetadata,\n RuntimeSyncSubtreeNode,\n} from \"@superblocksteam/library-shared/types\";\nimport type {\n SbElement,\n SbSelector,\n} from \"@superblocksteam/library-shared/types\";\n\ntype RuntimeComposite = RuntimeSyncComposite;\ntype RuntimeComponentData = RuntimeSyncComponentData;\ntype PathNode = RuntimeSyncComponentMetadata;\ntype SubtreeNode = RuntimeSyncSubtreeNode;\n\nexport type SubscribeParams = {\n sourceId: SbElement;\n};\n\nconst MAX_SUBTREE_DEPTH = 30;\n\nexport function buildComposite(\n editStore: EditStore,\n params: SubscribeParams,\n): RuntimeComposite | null {\n const { sourceId } = params;\n\n const runtimeStore = editStore.runtimeTrackingStore;\n\n const selectorIds =\n editStore.ui.getMostRelevantSelectorIdsForSourceId(sourceId);\n\n if (selectorIds.length === 0) {\n return null;\n }\n\n // if there are multiple, just select the first one\n const selectorId = selectorIds[0];\n\n const componentNode = runtimeStore.getComponent(selectorId);\n if (!componentNode) {\n return null;\n }\n\n const component: RuntimeComponentData = {\n selectorId: componentNode.selectorId,\n sourceId: componentNode.sourceId,\n type: getComponentType(componentNode),\n displayName: runtimeStore.getDisplayName(selectorId),\n isSbComponent: componentNode.isSbComponent,\n isHtmlElement: componentNode.isHtmlElement,\n props: componentNode.props,\n };\n\n const parentSelectorId = runtimeStore.getComponentParent(selectorId) as\n | SbSelector\n | undefined;\n const parent = parentSelectorId\n ? buildComponentData(runtimeStore, parentSelectorId)\n : null;\n\n const children = buildChildren(runtimeStore, selectorId);\n const path = buildPathToRoot(runtimeStore, selectorId);\n\n const subtreeRoot = buildSubtreeNode(\n runtimeStore,\n selectorId,\n MAX_SUBTREE_DEPTH,\n );\n\n return {\n component,\n parent,\n children,\n path,\n subtree: subtreeRoot ?? undefined,\n };\n}\n\nfunction buildComponentData(\n store: RuntimeTrackingStore,\n selectorId: SbSelector,\n): RuntimeComponentData | null {\n const componentNode = store.getComponent(selectorId);\n if (!componentNode) {\n return null;\n }\n\n return {\n selectorId: componentNode.selectorId,\n sourceId: componentNode.sourceId,\n type: getComponentType(componentNode),\n displayName: store.getDisplayName(selectorId),\n isSbComponent: componentNode.isSbComponent,\n isHtmlElement: componentNode.isHtmlElement,\n props: componentNode.props,\n };\n}\n\nfunction buildChildren(\n store: RuntimeTrackingStore,\n selectorId: SbSelector,\n): RuntimeComponentData[] {\n const childSelectorIds = store.getComponentChildren(selectorId);\n return childSelectorIds\n .map((childId) => buildComponentData(store, childId))\n .filter(Boolean) as RuntimeComponentData[];\n}\n\nfunction buildPathToRoot(\n store: RuntimeTrackingStore,\n selectorId: SbSelector,\n): PathNode[] {\n const path: PathNode[] = [];\n let current: SbSelector | undefined = selectorId;\n const visited = new Set<SbSelector>();\n\n while (current && !visited.has(current)) {\n visited.add(current);\n\n const component = store.getComponent(current);\n if (component && !component.noSelect) {\n path.unshift({\n selectorId: component.selectorId,\n sourceId: component.sourceId,\n displayName: store.getDisplayName(current),\n type: getComponentType(component),\n });\n }\n current = store.getComponentParent(current) as SbSelector | undefined;\n }\n\n if (current && visited.has(current)) {\n console.warn(\n `[RuntimeSync] Cycle detected in component graph at ${current}`,\n );\n }\n\n return path;\n}\n\nfunction buildSubtreeNode(\n store: RuntimeTrackingStore,\n selectorId: SbSelector,\n remainingDepth: number,\n): SubtreeNode | null {\n const component = store.getComponent(selectorId);\n if (!component) {\n return null;\n }\n\n const children: SubtreeNode[] = [];\n\n if (remainingDepth > 0) {\n const childSelectorIds = store.getComponentChildren(selectorId);\n for (const childId of childSelectorIds) {\n const childNode = buildSubtreeNode(store, childId, remainingDepth - 1);\n if (childNode) {\n children.push(childNode);\n }\n }\n }\n\n return {\n selectorId,\n sourceId: component.sourceId,\n displayName: store.getDisplayName(selectorId),\n type: getComponentType(component),\n children,\n };\n}\n\nfunction getComponentType(component: ComponentNode): string {\n if (typeof component.type === \"function\") {\n return component.type.name;\n }\n if (typeof component.type === \"string\") {\n return component.type;\n }\n return \"Component\";\n}\n","import { makeAutoObservable, observable, action, computed } from \"mobx\";\nimport { buildComposite } from \"./builders.js\";\nimport type { EditStore } from \"../edit-store.js\";\nimport type { RuntimeSyncComposite } from \"@superblocksteam/library-shared/types\";\nimport type { SbElement } from \"@superblocksteam/library-shared/types\";\n\n/**\n * MobX store that manages runtime component subscriptions.\n * Tracks which components are subscribed and builds fresh composites on-demand.\n * The subscriptions getter allows startEditorSync reactions to track deep observables\n * from buildComposite, eliminating the need for manual reaction management.\n */\nexport class RuntimeSubscriptionsStore {\n private subscribedSourceIds = observable.set<SbElement>();\n\n constructor(readonly editStore: EditStore) {\n makeAutoObservable(this, {\n subscribe: action,\n unsubscribe: action,\n clearAll: action,\n subscriptions: computed,\n });\n }\n\n subscribe(sourceId: SbElement): void {\n this.subscribedSourceIds.add(sourceId);\n }\n\n unsubscribe(sourceId: SbElement): void {\n this.subscribedSourceIds.delete(sourceId);\n }\n\n clearAll(): void {\n this.subscribedSourceIds.clear();\n }\n\n get subscriptions(): Record<SbElement, RuntimeSyncComposite | null> {\n const out: Record<SbElement, RuntimeSyncComposite | null> = {};\n this.subscribedSourceIds.forEach((sourceId) => {\n out[sourceId] = buildComposite(this.editStore, {\n sourceId,\n });\n });\n return out;\n }\n}\n","import { OBS_TAG_APPLICATION_ID } from \"@superblocksteam/shared\";\nimport { action, makeObservable, observable } from \"mobx\";\nimport posthog from \"posthog-js\";\nimport { isEditMode } from \"../lib/internal-details/is-edit-mode.js\";\nimport rootStore from \"../lib/internal-details/lib/root-store.js\";\nimport { AiManager } from \"./features/ai-store.js\";\nimport ConnectionManager from \"./features/connection-manager.js\";\nimport OperationManager from \"./features/operation-store.js\";\nimport PropertiesPanelManager from \"./features/properties-panel-manager.js\";\nimport RuntimeTrackingStore from \"./features/runtime-tracking-store.js\";\nimport UIStore from \"./features/ui-store.js\";\nimport { startEditorSync } from \"./mobx-sync/mobx-editor-sync.js\";\nimport { RuntimeSubscriptionsStore } from \"./runtime-sync/runtime-subscriptions-store.js\";\n\nimport { editorBridge } from \"./superblocks-editor-bridge.js\";\nimport type { RootStore } from \"../lib/internal-details/lib/root-store.js\";\nimport type {\n ViteMessageKind,\n ViteMessage,\n InteractionMode,\n} from \"@superblocksteam/library-shared/types\";\n\ndeclare global {\n interface Window {\n _SB_ENABLE_SESSION_RECORDING?: boolean;\n __SUPERBLOCKS_EDITOR_HOOK__: InstanceType<typeof EditStore>;\n }\n}\n\nconst isSessionRecordingEnabled = (): boolean => {\n return window._SB_ENABLE_SESSION_RECORDING ?? false;\n};\n\n// A single instance of this is created and attached to the root store when the app is using edit mode\nexport class EditStore {\n ui: UIStore;\n operationManager: OperationManager;\n propertiesPanelManager: PropertiesPanelManager;\n runtimeTrackingStore: RuntimeTrackingStore;\n connectionManager: ConnectionManager;\n ai: AiManager;\n runtimeSubscriptionsStore: RuntimeSubscriptionsStore;\n\n isInitialized = false;\n recordingInitialized = false;\n interactionMode: InteractionMode = \"interactive\";\n\n // for certain interactions around hotkeys\n lastInteractionMode: InteractionMode = \"interactive\";\n\n // Track if design mode should persist after Meta key release (locked after selection)\n isDesignModeLocked = false;\n\n private viteMessageListeners: Map<\n ViteMessageKind,\n Array<(message: any) => void>\n > = new Map();\n\n constructor(rootStore: RootStore) {\n this.ui = new UIStore(rootStore, this);\n this.operationManager = new OperationManager();\n this.propertiesPanelManager = new PropertiesPanelManager(\n this,\n rootStore.componentRegistry,\n );\n this.runtimeTrackingStore = new RuntimeTrackingStore(this);\n this.runtimeSubscriptionsStore = new RuntimeSubscriptionsStore(this);\n this.connectionManager = new ConnectionManager();\n this.ai = new AiManager(this.runtimeTrackingStore);\n makeObservable(this, {\n isInitialized: observable,\n interactionMode: observable,\n isDesignModeLocked: observable,\n setIsInitialized: action,\n setInteractionMode: action,\n setDesignModeLocked: action,\n });\n }\n\n setIsInitialized(isInitialized: boolean) {\n if (this.isInitialized) return;\n this.isInitialized = isInitialized;\n\n if (isInitialized) {\n startEditorSync({\n store: this.runtimeSubscriptionsStore,\n storeId: \"runtimeSync\",\n projection: (store) => store.subscriptions,\n });\n }\n }\n\n setInteractionMode(mode: InteractionMode, notifyEditor = false) {\n if (this.interactionMode === mode) {\n return;\n }\n\n this.lastInteractionMode = this.interactionMode;\n this.interactionMode = mode;\n\n // Reset design mode lock when entering design mode or exiting to other modes\n if (mode === \"design\") {\n this.isDesignModeLocked = false;\n } else if (this.lastInteractionMode === \"design\") {\n this.isDesignModeLocked = false;\n }\n\n if (notifyEditor) {\n editorBridge.setInteractionMode(mode);\n }\n }\n\n setDesignModeLocked(locked: boolean) {\n this.isDesignModeLocked = locked;\n }\n\n onViteMessage<\n T extends ViteMessageKind,\n Message extends Extract<ViteMessage, { kind: T }>,\n >(kind: T, callback: (message: Message) => void) {\n this.viteMessageListeners.set(kind, [\n ...(this.viteMessageListeners.get(kind) || []),\n callback,\n ]);\n\n return () => {\n this.viteMessageListeners.set(\n kind,\n this.viteMessageListeners.get(kind)?.filter((cb) => cb !== callback) ||\n [],\n );\n };\n }\n\n triggerViteMessage<\n T extends ViteMessageKind,\n Message extends Extract<ViteMessage, { kind: T }>,\n >(kind: T, message: Message) {\n this.viteMessageListeners.get(kind)?.forEach((cb) => cb(message));\n }\n\n startRecording(recording: {\n userId: string;\n appId: string;\n sessionRecordingKey: string;\n }) {\n if (this.recordingInitialized || !isSessionRecordingEnabled()) {\n return;\n }\n\n posthog.init(recording.sessionRecordingKey, {\n api_host: \"https://us.i.posthog.com\",\n defaults: \"2025-05-24\",\n session_recording: {\n recordCrossOriginIframes: true,\n },\n });\n posthog.identify(recording.userId);\n posthog.register({\n [OBS_TAG_APPLICATION_ID]: recording.appId,\n });\n this.recordingInitialized = true;\n }\n}\n\nif (!window.__SUPERBLOCKS_EDITOR_HOOK__ && isEditMode()) {\n // Singleton instance for global access to EditStore\n const editStore = new EditStore(rootStore);\n window.__SUPERBLOCKS_EDITOR_HOOK__ = editStore;\n rootStore.setEditStore(editStore);\n}\n\nexport function initializeEditStore() {\n if (!window.__SUPERBLOCKS_EDITOR_HOOK__) {\n return;\n }\n window.__SUPERBLOCKS_EDITOR_HOOK__.setIsInitialized(true);\n}\n","import { useHotkeys as useHotkeysOriginal } from \"react-hotkeys-hook\";\nimport type { KeyHandler } from \"hotkeys-js\";\nimport type { Options } from \"react-hotkeys-hook\";\n\nexport function useEditorHotkeys<T extends Element>(\n keys: string,\n callback: KeyHandler,\n options?: any[] | Options,\n deps?: any[],\n): React.MutableRefObject<T | null> | undefined {\n if (options instanceof Array) {\n deps = options;\n options = undefined;\n }\n\n return useHotkeysOriginal(keys, callback, options, [...(deps ?? []), false]);\n}\n","import { useEffect, useRef } from \"react\";\n\nexport function useKeyPressed(\n key: string,\n callback: (isPressed: boolean) => void,\n options?: {\n /** Delay in milliseconds before triggering the pressed callback. Default: 0 (immediate) */\n pressDelay?: number;\n /** Whether to allow multiple keys to be pressed at the same time. Default: true */\n allowMultipleKeys?: boolean;\n },\n) {\n const timeoutRef = useRef<NodeJS.Timeout | null>(null);\n const isKeyDownRef = useRef<boolean>(false);\n\n useEffect(() => {\n const handleKeyDown = (e: KeyboardEvent) => {\n if (e.key === key && !e.repeat) {\n if (\n ((e.ctrlKey && key.toLowerCase() !== \"ctrl\") ||\n (e.metaKey && key.toLowerCase() !== \"meta\") ||\n (e.altKey && key.toLowerCase() !== \"alt\") ||\n (e.shiftKey && key.toLowerCase() !== \"shift\")) &&\n !options?.allowMultipleKeys\n ) {\n if (timeoutRef.current) {\n clearTimeout(timeoutRef.current);\n timeoutRef.current = null;\n }\n isKeyDownRef.current = false;\n callback(false);\n return;\n }\n\n isKeyDownRef.current = true;\n\n if (options?.pressDelay && options.pressDelay > 0) {\n // Clear any existing timeout\n if (timeoutRef.current) {\n clearTimeout(timeoutRef.current);\n }\n\n // Set timeout for delayed execution\n timeoutRef.current = setTimeout(() => {\n callback(true);\n }, options.pressDelay);\n } else {\n // Immediate execution (default behavior)\n callback(true);\n }\n } else if (\n e.key !== key &&\n isKeyDownRef.current &&\n options?.allowMultipleKeys === false\n ) {\n // Another key was pressed while the target key is down\n if (timeoutRef.current) {\n clearTimeout(timeoutRef.current);\n timeoutRef.current = null;\n }\n callback(false);\n isKeyDownRef.current = false;\n }\n };\n\n const handleKeyUp = (e: KeyboardEvent) => {\n if (e.key === key) {\n // Clear timeout if key is released before delay\n if (timeoutRef.current) {\n clearTimeout(timeoutRef.current);\n timeoutRef.current = null;\n }\n\n isKeyDownRef.current = false;\n\n // Always execute release logic immediately\n callback(false);\n }\n };\n\n const handleVisibilityChange = () => {\n if (document.hidden) {\n isKeyDownRef.current = false;\n callback(false);\n }\n };\n\n const handleBlur = () => {\n isKeyDownRef.current = false;\n callback(false);\n };\n\n document.addEventListener(\"keydown\", handleKeyDown);\n document.addEventListener(\"keyup\", handleKeyUp);\n document.addEventListener(\"visibilitychange\", handleVisibilityChange);\n document.addEventListener(\"blur\", handleBlur);\n\n return () => {\n document.removeEventListener(\"keydown\", handleKeyDown);\n document.removeEventListener(\"keyup\", handleKeyUp);\n document.removeEventListener(\"visibilitychange\", handleVisibilityChange);\n document.removeEventListener(\"blur\", handleBlur);\n if (timeoutRef.current) {\n clearTimeout(timeoutRef.current);\n }\n };\n }, [key, callback, options?.pressDelay, options?.allowMultipleKeys]);\n}\n","import { computed, reaction } from \"mobx\";\nimport { useEffect, useMemo, useState, useRef } from \"react\";\nimport type { IComputedValue } from \"mobx\";\n\n/**\n * The component that uses this hook must be wrapped `observer`, otherwise state changes will not\n * cause this hook to re-run.\n */\nexport const useObserverMemo = <T>(fn: () => T, deps: any[]) => {\n return useMemo<IComputedValue<T>>(() => {\n return computed(fn);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, deps).get();\n};\n\n/**\n * Like useObserverMemo, but does not require the component to be wrapped in an observer.\n * It is recommended to use useObserverMemo instead.\n * @see useObserverMemo\n *\n * Note: This implementation uses MobX reactions to track both observable changes and\n * dependency changes.\n */\nexport const useStandaloneObserverMemo = <T>(fn: () => T, deps: any[]) => {\n const fnRef = useRef(fn);\n fnRef.current = fn;\n\n const [result, setResult] = useState<T>(fnRef.current);\n useEffect(\n () =>\n reaction(() => fnRef.current(), setResult, {\n fireImmediately: true,\n name: \"useStandaloneObserverMemo\",\n }),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n deps,\n );\n\n return result;\n};\n","enum Indices {\n Layer0 = 60,\n Layer1,\n Layer2,\n Layer3,\n Layer4,\n Layer5,\n Layer6,\n Layer7,\n Layer8,\n Layer9,\n Layer10,\n Layer11,\n Layer12,\n Layer13,\n Layer14,\n LayerMax = 99999,\n}\n\n// the inside canvas layers and outside layers will not interfere with each other\n// TODO: split them into two Layer objects\nexport const Layers = {\n //-------------- inside canvas --------------\n\n dragPreview: Indices.Layer1,\n\n visibilityOverlay: Indices.Layer4,\n selectedRect: Indices.Layer4, // interaction rect\n focusedRect: Indices.Layer5,\n namePill: Indices.Layer6, // interaction rect name pill\n\n closeButton: Indices.Layer4, // modal or slideout close button\n stickySections: Indices.Layer3,\n scrollbars: Indices.Layer5, // for ScrollContainer, inside positionedWidget\n componentBorder: Indices.Layer3, // for containers\n resizeWrapper: Indices.Layer4, // inside positioned widget, always show\n // only show when focused/selected, in parallel with widgetName\n // selectedWrapper: Indices.Layer4,\n\n parentSelectedWrapper: Indices.Layer3,\n widgetResizer: Indices.Layer4, // widget resizer which is 4 edges and 4 corners\n // TODO: refactor the resizer below, looks like some is not needed.\n resizer: Indices.Layer6, // section column resizer and resizer disabled tooltip,\n dialog: Indices.Layer7, // for dialog component or detached components (such as slideouts, modals)\n\n widgetName: Indices.Layer4,\n selectionConstraintResize: Indices.Layer4, // min max height constraint\n canvasBreadCrumbPopover: Indices.Layer5,\n // layers for vstack dnd\n vstackDropPlaceholder: Indices.Layer2,\n focusedInput: Indices.Layer14, // blueprint control group focused input\n\n max: Indices.LayerMax,\n};\n","import {\n SELECTOR_ID_ATTRIBUTE,\n SOURCE_ID_ATTRIBUTE,\n} from \"@superblocksteam/library-shared\";\nimport type {\n SbElement,\n SbSelector,\n} from \"@superblocksteam/library-shared/types\";\n\nexport const getBoundingBoxForWidget = (selectorId: SbSelector) => {\n return getWidgetNode(selectorId)?.getBoundingClientRect();\n};\n\n/**\n * Get the DOM node for a widget by either selector ID or source ID.\n *\n * In the frameworkless component world, raw components may not have instance IDs\n * in the DOM, but they always have source IDs. This function handles both cases.\n *\n * @param idOrSourceId - Either a selector ID (starts with \"S-\") or source ID (starts with \"SB-\")\n * @returns The DOM element or null if not found\n */\nexport const getWidgetNode = (\n idOrSourceId: SbSelector | SbElement,\n): HTMLElement | null => {\n const isSelectorId = idOrSourceId.startsWith(\"S-\");\n const isSourceId = idOrSourceId.startsWith(\"SB-\");\n if (isSelectorId) {\n const element = document?.querySelector(\n `[${SELECTOR_ID_ATTRIBUTE}=\"${idOrSourceId}\"]`,\n ) as HTMLElement | null;\n return element;\n } else if (isSourceId) {\n // Fallback to source ID lookup (works for raw frameworkless components)\n return document?.querySelector(\n `[${SOURCE_ID_ATTRIBUTE}=\"${idOrSourceId}\"]`,\n ) as HTMLElement | null;\n }\n\n throw new Error(`Unknown ID format: ${idOrSourceId} (expected S-* or SB-*)`);\n};\n\nexport const getComputedStyle = (\n selectorId: SbSelector,\n): CSSStyleDeclaration | null => {\n if (typeof window === \"undefined\") {\n return null;\n }\n\n try {\n const element = document.querySelector(\n `[${SELECTOR_ID_ATTRIBUTE}=\"${selectorId}\"]`,\n ) as HTMLElement | null;\n if (!element) {\n return null;\n }\n return window.getComputedStyle(element);\n } catch {\n return null;\n }\n};\n\nexport const getFlexDirection = (\n computedStyles: CSSStyleDeclaration | null,\n): \"row\" | \"column\" | undefined => {\n if (!computedStyles) {\n return undefined;\n }\n\n try {\n const display = computedStyles.display;\n\n if (display !== \"flex\" && display !== \"inline-flex\") {\n // TODO: Handle other display types\n return undefined;\n }\n\n const flexDirection = computedStyles.flexDirection;\n if (flexDirection === \"column\" || flexDirection === \"column-reverse\") {\n return \"column\";\n } else if (flexDirection === \"row\" || flexDirection === \"row-reverse\") {\n return \"row\";\n }\n\n return \"row\"; // Default flex direction\n } catch {\n return undefined;\n }\n};\n","import { observer } from \"mobx-react-lite\";\nimport { getEditStore } from \"../get-edit-store.js\";\nimport { editorBridge } from \"../superblocks-editor-bridge.js\";\nimport type { SbSelector } from \"@superblocksteam/library-shared/types\";\n\nconst NamePillDiv = (params: {\n displayName: string;\n selectorId: SbSelector;\n type: \"SELECTED\" | \"FOCUSED\" | \"TARGETED\";\n}) => {\n const { displayName, type, selectorId } = params;\n\n const sourceId = getEditStore().runtimeTrackingStore.getSourceId(selectorId);\n\n const shouldToggleComponentInAiContext =\n getEditStore().ai.shouldToggleComponentInAiContext();\n\n return (\n <div\n className=\"sb-edit-selection-name-pill\"\n data-test=\"interaction-rect-name-pill\"\n data-pill-name={displayName}\n data-pill-type={type}\n onPointerDown={(e) => {\n e.stopPropagation();\n }}\n onClick={(ev) => {\n ev.stopPropagation();\n ev.preventDefault();\n\n if (shouldToggleComponentInAiContext) {\n if (sourceId) {\n editorBridge.toggleComponentInAiContext(\n sourceId,\n selectorId,\n displayName,\n );\n }\n } else {\n getEditStore().ui.selectWidget(selectorId, ev.shiftKey === true);\n }\n }}\n >\n {displayName}\n </div>\n );\n};\n\ninterface NamePillProps {\n selectorId: SbSelector;\n displayName: string;\n type: \"SELECTED\" | \"FOCUSED\" | \"TARGETED\";\n}\n\nconst NamePill: ReturnType<typeof observer<NamePillProps>> = observer(\n (props: NamePillProps) => {\n const { selectorId, displayName, type } = props;\n\n return (\n <NamePillDiv\n displayName={displayName}\n selectorId={selectorId}\n type={type}\n />\n );\n },\n);\n\nexport default NamePill;\n","import {\n AiContextMode,\n type SbSelector,\n} from \"@superblocksteam/library-shared/types\";\nimport { useObserverMemo } from \"../../lib/hooks/use-observer-memo.js\";\nimport { Layers } from \"../../lib/user-facing/layers.js\";\nimport { getWidgetRectAnchorName } from \"../../lib/utils/widget-wrapper-naming.js\";\nimport { getEditStore } from \"../get-edit-store.js\";\nimport { getWidgetNode } from \"../interaction-utils.js\";\nimport NamePill from \"./interaction-rect-name-pill.js\";\n\n// This might be overkill but it feels OK to use.\n// Ranges from 0 to 1, where 0 is no overlap and 1 is full overlap\nconst guessOverlapAmountForNamePills = (\n selector1: SbSelector,\n selector2: SbSelector,\n) => {\n const renderedTag1 =\n getEditStore().runtimeTrackingStore.getFirstAnchorableTag(selector1);\n const renderedTag2 =\n getEditStore().runtimeTrackingStore.getFirstAnchorableTag(selector2);\n const rect1 = renderedTag1\n ? getWidgetNode(renderedTag1)?.getBoundingClientRect()\n : null;\n const rect2 = renderedTag2\n ? getWidgetNode(renderedTag2)?.getBoundingClientRect()\n : null;\n if (!rect1 || !rect2) {\n return 0;\n }\n // name pills are about 22px tall, and 70px+ wide depending on text length\n if (Math.abs(rect1.top - rect2.top) > 36) {\n return 0;\n }\n const xDelta = Math.abs(rect1.right - rect2.right);\n if (xDelta > 200) {\n return 0;\n }\n return 1 - xDelta / 200;\n};\nconst useOverlapWithOtherPillInfo = (selectorId: SbSelector) => {\n const focusedSelectorId = getEditStore().ui.getFocusedSelectorId();\n const selectorIsFocused = focusedSelectorId === selectorId;\n const somethingElseIsFocused =\n focusedSelectorId != null && !selectorIsFocused;\n const opacityValue = somethingElseIsFocused\n ? Math.min(\n 0.6,\n 1 - guessOverlapAmountForNamePills(focusedSelectorId, selectorId),\n )\n : 1;\n return opacityValue;\n};\n\nexport function InteractionRectActions(props: {\n selectorId: SbSelector;\n displayName: string;\n type: \"SELECTED\" | \"FOCUSED\" | \"TARGETED\";\n transform?: string;\n}) {\n const { selectorId, displayName, type, transform } = props;\n\n const isPrimarySelectorId = useObserverMemo(() => {\n const focusedSelectorId = getEditStore().ui.getFocusedSelectorId();\n const selectedSelectorIds = getEditStore().ui.getSelectedSelectorIds();\n\n if (type === \"SELECTED\") {\n return selectedSelectorIds.includes(selectorId);\n } else if (type === \"FOCUSED\") {\n return focusedSelectorId === selectorId;\n } else {\n return getEditStore().ai.isTargetedSelector(selectorId);\n }\n }, [type, selectorId]);\n\n const opacityValue = useOverlapWithOtherPillInfo(selectorId);\n\n if (!isPrimarySelectorId) {\n return null;\n }\n\n const aiContextMode = getEditStore().ai.getAiContextMode();\n const isAiTaggingEnabled = getEditStore().ai.getIsTaggingEnabled();\n\n const shouldHideActions = !isPrimarySelectorId;\n\n const shouldShowAiPurplePill =\n isAiTaggingEnabled &&\n (aiContextMode === AiContextMode.AUTO_SELECT ||\n (aiContextMode === AiContextMode.HIGHLIGHT && type === \"TARGETED\"));\n\n const renderedTagSelectorId =\n getEditStore().runtimeTrackingStore.getFirstAnchorableTag(selectorId);\n\n return (\n <div\n className={`sb-edit-interaction-rect-actions ${shouldShowAiPurplePill ? \"sb-edit-actions-target-mode\" : \"\"}`}\n data-sb-actions-selector-id={selectorId}\n data-sb-actions-source-id={getEditStore().runtimeTrackingStore.getSourceId(\n selectorId,\n )}\n data-test=\"sb-name-pill-container\"\n style={\n {\n ...(shouldHideActions ? { display: \"none !important\" } : {}),\n position: \"fixed\",\n bottom: \"anchor(top)\",\n right: \"anchor(right)\",\n positionAnchor: getWidgetRectAnchorName(\n renderedTagSelectorId ?? selectorId,\n ),\n visibility: \"visible\",\n marginTop: \"1px\",\n paddingBottom: \"1px\",\n zIndex: Layers.namePill,\n pointerEvents: \"all\",\n display: \"flex\",\n gap: \"2px\",\n opacity: opacityValue,\n transform,\n } as React.CSSProperties\n }\n >\n <NamePill selectorId={selectorId} displayName={displayName} type={type} />\n </div>\n );\n}\n","import { SELECTOR_ID_ATTRIBUTE } from \"@superblocksteam/library-shared\";\nimport { useEffect, useState } from \"react\";\nimport type { SbSelector } from \"@superblocksteam/library-shared/types\";\n\ninterface TransformData {\n transform: string;\n transformedElementRect?: DOMRect; // Store for percentage calculations\n}\n\nconst transformCache = new Map<SbSelector, TransformData>();\n\n/*\ncss anchor positioning doesn't take into account translate/transform as these are considered post-layout effects\ntranslations/transforms affect their children, so for a given element, we traverse upwards from that element collecting transforms\nthen we convert all from percentage to px if needed, and return them to be applied on interaction-rects \nthis is cached for performance reasons\n*/\nexport function useAnchorTransform(selectorId: SbSelector | undefined) {\n const [transformData, setTransformData] = useState<TransformData>(() => {\n if (!selectorId) return { transform: \"none\" };\n return transformCache.get(selectorId) ?? { transform: \"none\" };\n });\n\n useEffect(() => {\n const calculateTransform = () => {\n if (!selectorId) {\n setTransformData({ transform: \"none\" });\n return;\n }\n\n // Clear cache on window resize to force recalculation\n if (transformCache.has(selectorId)) {\n transformCache.delete(selectorId);\n }\n\n const element = document.querySelector(\n `[${SELECTOR_ID_ATTRIBUTE}=\"${selectorId}\"]`,\n ) as HTMLElement | null;\n if (!element) return;\n\n // Collect ALL transforms from the element and ancestors\n const transforms: Array<{ computed: string; element: HTMLElement }> = [];\n let current: HTMLElement | null = element;\n\n while (current && current !== document.body) {\n const computedStyle = getComputedStyle(current);\n\n // Check both transform and translate properties\n const transform = computedStyle.transform;\n const translate = computedStyle.translate;\n\n if (transform && transform !== \"none\") {\n transforms.push({ computed: transform, element: current });\n }\n if (translate && translate !== \"none\") {\n // Convert translate to transform for consistency\n transforms.push({\n computed: `translate(${translate})`,\n element: current,\n });\n }\n\n current = current.parentElement;\n }\n\n if (transforms.length === 0) {\n const data: TransformData = { transform: \"none\" };\n transformCache.set(selectorId, data);\n setTransformData(data);\n return;\n }\n\n // For percentage-based transforms, we need the element's dimensions\n // Use the FIRST transformed ancestor (closest to anchor element)\n const firstTransformedElement = transforms[0].element;\n const rect = firstTransformedElement.getBoundingClientRect();\n\n // Combine transforms by applying the computed transform matrix\n // The browser already handles the composition for us via getComputedStyle\n const finalTransform = transforms[0].computed;\n\n // Convert percentage-based translates to pixels\n const processedTransform = convertPercentageInTransform(\n finalTransform,\n rect.width,\n rect.height,\n );\n\n const data: TransformData = {\n transform: processedTransform,\n transformedElementRect: rect,\n };\n\n transformCache.set(selectorId, data);\n setTransformData(data);\n };\n\n // Calculate transform initially\n calculateTransform();\n\n // Add window resize listener to recalculate on window size changes\n const handleResize = () => {\n calculateTransform();\n };\n\n window.addEventListener(\"resize\", handleResize);\n window.addEventListener(\"scroll\", handleResize);\n\n // Cleanup\n return () => {\n window.removeEventListener(\"resize\", handleResize);\n window.removeEventListener(\"scroll\", handleResize);\n };\n }, [selectorId]);\n\n return transformData.transform;\n}\n\nexport function convertPercentageInTransform(\n transformValue: string,\n width: number,\n height: number,\n): string {\n // Handle matrix/matrix3d - extract translate components\n if (transformValue.startsWith(\"matrix\")) {\n return transformValue; // Already in absolute values\n }\n\n // Handle translate() or translate3d()\n const translateMatch = transformValue.match(/translate3?d?\\(([^)]+)\\)/);\n if (!translateMatch) return transformValue;\n const valueString = translateMatch[1].trim();\n const values = valueString.includes(\",\")\n ? valueString.split(\",\").map((v) => v.trim())\n : valueString.split(/\\s+/).filter((v) => v);\n\n const convertValue = (value: string, dimension: number): string => {\n if (value.includes(\"%\")) {\n const percentage = parseFloat(value);\n return `${Math.round((percentage / 100) * dimension)}px`;\n }\n return value;\n };\n\n const x = convertValue(values[0] || \"0\", width);\n const y = values[1] ? convertValue(values[1], height) : \"0px\";\n const z = values[2] || \"0px\";\n\n // Reconstruct the transform with the px values\n if (values.length > 2) {\n return transformValue.replace(\n translateMatch[0],\n `translate3d(${x}, ${y}, ${z})`,\n );\n }\n return transformValue.replace(translateMatch[0], `translate(${x}, ${y})`);\n}\n\nexport function clearTransformCache(selectorId?: SbSelector) {\n if (selectorId) {\n transformCache.delete(selectorId);\n } else {\n transformCache.clear();\n }\n}\n","import {\n AiContextMode,\n type SbElement,\n type SbSelector,\n} from \"@superblocksteam/library-shared/types\";\nimport React, { useMemo } from \"react\";\nimport { useObserverMemo } from \"../../lib/hooks/use-observer-memo.js\";\nimport { Layers } from \"../../lib/user-facing/layers.js\";\nimport {\n getWidgetAnchorName,\n getWidgetRectAnchorName,\n} from \"../../lib/utils/widget-wrapper-naming.js\";\n\nimport { getEditStore } from \"../get-edit-store.js\";\nimport { InteractionRectActions } from \"./interaction-rect-actions.jsx\";\nimport { useAnchorTransform } from \"./transform-utils.js\";\nimport type { InteractionMode } from \"@superblocksteam/library-shared/types\";\nimport type { CSSProperties } from \"react\";\n\nexport type SelectionInfo = {\n sourceId: SbElement;\n selectorId: SbSelector;\n displayName: string;\n selectionType: \"SELECTED\" | \"FOCUSED\" | \"TARGETED\";\n type: string | undefined;\n};\n\n// TODO (alex): show different rects for sourceId and instanceId - for now just using instanceId\nexport const useSelectionElements = (params: {\n focusedSourceId: SbElement | null;\n focusedSelectorId: SbSelector | null;\n selectedSourceIds: SbElement[];\n selectedSelectorIds: SbSelector[];\n targetedSourceIds: SbElement[];\n aiContextMode: AiContextMode;\n interactionMode: InteractionMode;\n}): SelectionInfo[] => {\n const {\n focusedSelectorId,\n selectedSourceIds,\n selectedSelectorIds,\n targetedSourceIds,\n aiContextMode,\n interactionMode,\n } = params;\n\n const allTargetedComponents = useMemo(() => {\n const components: { selectorId: SbSelector; sourceId: SbElement }[] = [];\n targetedSourceIds.forEach((sourceId) => {\n const selectorIds =\n getEditStore().runtimeTrackingStore.getSelectorIdsForSourceId(sourceId);\n components.push(\n ...Array.from(selectorIds).map((selectorId) => ({\n selectorId,\n sourceId,\n })),\n );\n });\n return components;\n }, [targetedSourceIds]);\n\n // TODO - restore viewport intersection\n const visibleTargetedComponents = allTargetedComponents;\n\n const selectionRects = useObserverMemo<SelectionInfo[]>(() => {\n const selectedRects: SelectionInfo[] = [];\n\n visibleTargetedComponents.forEach((component) => {\n const { type, displayName } = selectDisplayNameAndVisibility(\n component.selectorId,\n );\n\n selectedRects.push({\n sourceId: component.sourceId,\n selectorId: component.selectorId,\n displayName,\n selectionType: \"TARGETED\",\n type,\n } satisfies SelectionInfo);\n });\n\n selectedSourceIds.forEach((sourceId) => {\n const selectorIds =\n interactionMode === \"design\"\n ? getEditStore().runtimeTrackingStore.getSelectorIdsForSourceId(\n sourceId,\n )\n : selectedSelectorIds;\n\n selectorIds.forEach((selectorId) => {\n const component =\n getEditStore().runtimeTrackingStore.getComponent(selectorId);\n if (component && !targetedSourceIds.includes(component.sourceId)) {\n const displayName =\n getEditStore().runtimeTrackingStore.getDisplayName(selectorId);\n selectedRects.push({\n sourceId,\n selectorId: selectorId,\n displayName: displayName,\n selectionType: \"SELECTED\",\n type: displayName,\n } satisfies SelectionInfo);\n }\n });\n });\n\n if (\n focusedSelectorId &&\n (aiContextMode === AiContextMode.AUTO_SELECT ||\n (!selectedSelectorIds.includes(focusedSelectorId) &&\n interactionMode === \"design\"))\n ) {\n const { type, displayName, sourceId } =\n selectDisplayNameAndVisibility(focusedSelectorId);\n\n if (sourceId) {\n selectedRects.push({\n selectorId: focusedSelectorId,\n sourceId: sourceId ?? (focusedSelectorId as SbElement),\n displayName,\n selectionType: \"FOCUSED\",\n type,\n } satisfies SelectionInfo);\n }\n }\n return selectedRects;\n }, [\n visibleTargetedComponents,\n selectedSourceIds,\n selectedSelectorIds,\n focusedSelectorId,\n aiContextMode,\n targetedSourceIds,\n interactionMode,\n ]);\n\n return selectionRects;\n};\n\nexport const InteractionRectTargetBorder = ({\n selectorId,\n}: {\n selectorId: SbSelector;\n}) => {\n const renderedTagSelectorId =\n getEditStore().runtimeTrackingStore.getFirstAnchorableTag(selectorId);\n return (\n <div\n className=\"sb-target-mode-border\"\n style={\n {\n positionAnchor: getWidgetAnchorName(\n renderedTagSelectorId ?? selectorId,\n ),\n zIndex: Layers.focusedRect,\n } as CSSProperties\n }\n >\n <div className=\"sb-target-mode-border-top-right\" />\n <div className=\"sb-target-mode-border-top-left\" />\n <div className=\"sb-target-mode-border-bottom-right\" />\n <div className=\"sb-target-mode-border-bottom-left\" />\n </div>\n );\n};\n\nexport const InteractionRect = (props: {\n displayName: string;\n sourceId: SbElement;\n selectorId: SbSelector;\n selectionType: \"SELECTED\" | \"FOCUSED\" | \"TARGETED\";\n hideRectBorder?: boolean;\n type?: string;\n}) => {\n const { selectionType, selectorId } = props;\n\n const parentSelectorId =\n getEditStore().runtimeTrackingStore.getNearestSelectableAncestor(\n selectorId,\n );\n const renderedParentTagSelectorId = parentSelectorId\n ? getEditStore().runtimeTrackingStore.getFirstAnchorableTag(\n parentSelectorId,\n )\n : undefined;\n\n const renderedTagSelectorId =\n getEditStore().runtimeTrackingStore.getFirstAnchorableTag(selectorId);\n\n const aiContextMode = getEditStore().ai.getAiContextMode();\n const isAiTargeted =\n aiContextMode === AiContextMode.AUTO_SELECT ||\n aiContextMode === AiContextMode.HIGHLIGHT;\n\n const selectionClass =\n selectionType === \"FOCUSED\"\n ? \"sb-edit-focus\"\n : selectionType === \"TARGETED\"\n ? \"sb-edit-target\"\n : \"\";\n\n // get any transforms on the anchor element and apply them to the rect\n const transform = useAnchorTransform(renderedTagSelectorId ?? selectorId);\n const parentTransform = useAnchorTransform(\n renderedParentTagSelectorId ?? parentSelectorId,\n );\n\n // TODO: remove this comment\n return (\n <>\n {parentSelectorId && selectionType === \"SELECTED\" && (\n <>\n <div\n className=\"sb-edit-selection-rect\"\n data-sb-selection-type={selectionType}\n style={\n {\n position: \"fixed\",\n top: \"anchor(top)\",\n left: \"anchor(left)\",\n right: \"anchor(right)\",\n bottom: \"anchor(bottom)\",\n anchorName: getWidgetRectAnchorName(\n renderedParentTagSelectorId ?? parentSelectorId,\n ),\n positionAnchor: getWidgetAnchorName(\n renderedParentTagSelectorId ?? parentSelectorId,\n ),\n border: \"1px dashed var(--primary-rect-color)\",\n ...(props.hideRectBorder ? { border: \"none\" } : {}),\n zIndex: Layers.selectedRect,\n transform: parentTransform,\n } as any\n }\n />\n </>\n )}\n <div\n className={`sb-edit-selection-rect ${selectionClass} ${aiContextMode === AiContextMode.AUTO_SELECT ? \"sb-edit-target-mode\" : \"\"}`}\n style={\n {\n position: \"fixed\",\n top: \"anchor(top)\",\n left: \"anchor(left)\",\n right: \"anchor(right)\",\n bottom: \"anchor(bottom)\",\n anchorName: getWidgetRectAnchorName(\n renderedTagSelectorId ?? selectorId,\n ),\n positionAnchor: getWidgetAnchorName(\n renderedTagSelectorId ?? selectorId,\n ),\n ...(props.hideRectBorder ? { border: \"none\" } : {}),\n zIndex:\n selectionType === \"FOCUSED\"\n ? Layers.focusedRect\n : Layers.selectedRect,\n transform,\n } as any\n }\n />\n {/* TODO(frameworkless): restore resizing handles\n <InteractionRectHandles\n selectorId={selectorId}\n selectionType={selectionType}\n /> */}\n {isAiTargeted ? (\n selectionType === \"TARGETED\" ? (\n <InteractionRectTargetBorder selectorId={selectorId} />\n ) : null\n ) : null}\n <InteractionRectActions\n selectorId={selectorId}\n displayName={props.displayName}\n type={selectionType}\n transform={transform}\n />\n </>\n );\n};\n\nexport const selectDisplayNameAndVisibility = (\n selectorId: SbSelector,\n): {\n type: string | undefined;\n displayName: string;\n sourceId?: SbElement;\n} => {\n const component =\n getEditStore().runtimeTrackingStore.getComponent(selectorId);\n const sourceId = component?.sourceId;\n const type = component?.type;\n\n const displayName =\n getEditStore().runtimeTrackingStore.getDisplayName(selectorId) ||\n (typeof type === \"string\" ? type : type?.displayName || type?.name) ||\n \"Unknown\";\n\n return {\n type: typeof type === \"string\" ? type : type?.displayName || type?.name,\n displayName,\n sourceId,\n };\n};\n","import { AiContextMode } from \"@superblocksteam/library-shared/types\";\nimport { useEditorHotkeys } from \"../lib/hooks/use-editor-hotkeys.js\";\nimport { useKeyPressed } from \"../lib/hooks/use-key-pressed.js\";\nimport { getEditStore } from \"./get-edit-store.js\";\nimport { selectDisplayNameAndVisibility } from \"./interaction-layer/interaction-rect.js\";\nimport { editorBridge } from \"./superblocks-editor-bridge.js\";\n\nexport function EditorHotkeys({ children }: { children: React.ReactNode }) {\n useEditorHotkeys(\n \"ctrl+z, command+z\",\n (e: any) => {\n e.preventDefault();\n e.stopPropagation();\n editorBridge.undo();\n },\n {\n filterPreventDefault: false,\n },\n [],\n );\n useEditorHotkeys(\n \"c\",\n (e: any) => {\n e.preventDefault();\n e.stopPropagation();\n const selectedSourceIds = getEditStore().ui.getSelectedSourceIds();\n const selectedSelectorIds = getEditStore().ui.getSelectedSelectorIds();\n if (selectedSourceIds.length > 0) {\n editorBridge.toggleComponentInAiContext(\n selectedSourceIds[0],\n selectedSelectorIds[0],\n selectDisplayNameAndVisibility(selectedSelectorIds[0])?.displayName,\n );\n }\n },\n {\n filterPreventDefault: false,\n },\n [],\n );\n\n useEditorHotkeys(\n \"ctrl+shift+z, command+shift+z\",\n (e: any) => {\n e.preventDefault();\n e.stopPropagation();\n editorBridge.redo();\n },\n {\n filterPreventDefault: false,\n },\n [],\n );\n\n useEditorHotkeys(\"backspace, delete\", (e: any) => {\n e.preventDefault();\n e.stopPropagation();\n\n if (\n e.target instanceof HTMLInputElement ||\n e.target instanceof HTMLTextAreaElement\n ) {\n return;\n }\n const editStore = getEditStore();\n editStore.operationManager.deleteComponents(\n editStore.ui.getSelectedSourceIds(),\n );\n editStore.ui.selectWidget(null);\n });\n\n useKeyPressed(\n \"Meta\",\n (isPressed) => {\n if (isPressed) {\n editorBridge.setAiContextMode(AiContextMode.AUTO_SELECT);\n } else {\n editorBridge.setAiContextMode(AiContextMode.SILENT);\n }\n },\n { pressDelay: 100, allowMultipleKeys: false },\n );\n\n useEditorHotkeys(\n \"Meta+i, command+i\",\n (e) => {\n e.preventDefault();\n e.stopPropagation();\n const editStore = getEditStore();\n editStore.ui.selectWidget(null);\n editStore.ui.setFocusedIds(null);\n editStore.setInteractionMode(\"interactive\", true);\n },\n { enableOnTags: [\"TEXTAREA\", \"INPUT\"], enableOnContentEditable: true },\n );\n\n useEditorHotkeys(\n \"Meta+d, command+d\",\n (e) => {\n e.preventDefault();\n e.stopPropagation();\n const editStore = getEditStore();\n editorBridge.setAiContextMode(AiContextMode.SILENT);\n editStore.setInteractionMode(\"design\", true);\n },\n {\n enableOnTags: [\"TEXTAREA\", \"INPUT\"],\n enableOnContentEditable: true,\n },\n );\n\n useEditorHotkeys(\n \"esc\",\n (e: any) => {\n e.preventDefault();\n e.stopPropagation();\n const editStore = getEditStore();\n editStore.ui.selectWidget(null);\n editStore.setInteractionMode(\"interactive\", true);\n editorBridge.setAiContextMode(AiContextMode.SILENT);\n },\n {\n enableOnTags: [\"TEXTAREA\", \"INPUT\"],\n enableOnContentEditable: true,\n },\n );\n\n useEditorHotkeys(\n \"ctrl+s, command+s\",\n (e: any) => {\n e.preventDefault();\n e.stopPropagation();\n const editStore = getEditStore();\n editStore.ui.selectWidget(null);\n editorBridge.setAiContextMode(AiContextMode.SILENT);\n const lastInteractionMode = editStore.lastInteractionMode;\n if (\n editStore.interactionMode === \"interactive\" ||\n editStore.interactionMode === \"design\"\n ) {\n editStore.setInteractionMode(\"full-preview\", true);\n } else {\n editStore.setInteractionMode(lastInteractionMode, true);\n }\n },\n {\n enableOnTags: [\"TEXTAREA\", \"INPUT\", \"SELECT\"],\n enableOnContentEditable: true,\n },\n );\n\n return <>{children}</>;\n}\n","import { isEditMode } from \"../lib/internal-details/is-edit-mode.js\";\nimport { iframeMessageHandler } from \"../lib/internal-details/lib/iframe.js\";\nimport { editorBridge } from \"./superblocks-editor-bridge.js\";\nimport type { IframeEventHandler } from \"../lib/internal-details/lib/iframe.js\";\n\n/**\n * Handles screenshot capture requests from the parent editor.\n * Only available in edit mode - modern-screenshot is not bundled in deployed apps.\n */\nexport function initializeScreenshotHandler() {\n if (!isEditMode()) {\n // Don't register handler in non-edit mode\n return;\n }\n\n const handleCaptureScreenshot: IframeEventHandler<\n \"capture-screenshot\"\n > = async ({ data }) => {\n const { callbackId } = data.payload;\n\n try {\n // Dynamically import modern-screenshot only when this handler is called (edit mode only)\n // Modern bundlers (Rollup/esbuild) will create a separate chunk for this import\n // Since initializeScreenshotHandler() returns early in non-edit mode,\n // this import() is never executed in deployed apps, so the chunk is never loaded\n const { domToWebp } = await import(\"modern-screenshot\");\n\n console.log(\"[Library Screenshot Handler] Capturing screenshot now...\");\n\n // Capture screenshot of the document body\n const dataUrl = await domToWebp(document.body, {\n backgroundColor: \"#ffffff\",\n });\n\n console.log(\n \"[Library Screenshot Handler] Screenshot captured successfully\",\n );\n\n // Send response back to parent\n editorBridge.sendCaptureScreenshotResponse(callbackId, dataUrl);\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n console.error(\n \"[Library Screenshot Handler] Error capturing screenshot:\",\n errorMessage,\n error,\n );\n\n // Send error response back to parent\n editorBridge.sendCaptureScreenshotResponse(\n callbackId,\n undefined,\n errorMessage,\n );\n }\n };\n\n // Register the handler\n iframeMessageHandler.addEventListener(\n \"capture-screenshot\",\n handleCaptureScreenshot,\n );\n}\n","import {\n AiGenerationState,\n ViteMessageKind,\n type SbElement,\n} from \"@superblocksteam/library-shared/types\";\nimport { observer } from \"mobx-react-lite\";\nimport React, { useEffect, useMemo, useRef, useState } from \"react\";\nimport { generatePath, useLocation, useNavigate } from \"react-router\";\nimport { handleBootstrapResponse } from \"../lib/internal-details/handle-bootstrap-response.js\";\nimport { FullPageSpinner } from \"../lib/internal-details/internal-components/spinner.jsx\";\nimport { isEditMode } from \"../lib/internal-details/is-edit-mode.js\";\nimport ApiHmrTracker from \"../lib/internal-details/lib/features/api-hmr-tracker.js\";\nimport { useGetCurrentUserQuery } from \"../lib/internal-details/lib/features/injected-features.js\";\nimport {\n isEmbeddedBySuperblocksFirstParty,\n iframeMessageHandler,\n} from \"../lib/internal-details/lib/iframe.js\";\nimport rootStore from \"../lib/internal-details/lib/root-store.js\";\nimport { useSuperblocksContext } from \"../lib/internal-details/superblocks-context.js\";\nimport { getApiPath } from \"../lib/internal-details/use-api.js\";\nimport { generateId } from \"../lib/utils/generate-id.js\";\nimport { initTracerProviderWithOrigin } from \"../lib/utils.js\";\nimport { BuildErrorNotification } from \"./build-error-notification.jsx\";\nimport createComponent from \"./create-component.js\";\nimport { initializeEditStore } from \"./edit-store.js\";\nimport { EditorHotkeys } from \"./editor-hotkeys.jsx\";\nimport { getEditStore } from \"./get-edit-store.js\";\nimport { initializeScreenshotHandler } from \"./screenshot-handler.js\";\nimport sourceUpdateApi from \"./source-update-api.js\";\nimport { editorBridge } from \"./superblocks-editor-bridge.js\";\nimport type { IframeEventHandler } from \"../lib/internal-details/lib/iframe.js\";\nimport type { MessageAction } from \"../lib/user-facing/types.js\";\nimport type { SbSelector } from \"@superblocksteam/library-shared/types\";\n\nlet _setReloadKey: (fn: (currentKey: number) => number) => void;\n\n/**\n * Triggers an HMR-style reload by incrementing the reload key.\n * This causes React to remount all children without a full page reload.\n * @param sendReadyAfter - If true, sends sb-ready after the remount completes\n */\nfunction triggerHmrReload(sendReadyAfter: boolean = false) {\n ApiHmrTracker.dontSkipUntilNextReload();\n _setReloadKey((currentKey) => currentKey + 1);\n\n if (sendReadyAfter) {\n // Wait for React to finish re-rendering before signaling ready\n requestAnimationFrame(() => {\n requestAnimationFrame(() => {\n editorBridge.sendReady();\n });\n });\n }\n}\n\nif (import.meta.hot) {\n import.meta.hot.on(\"sb:force-remount-after-reload\", () => {\n ApiHmrTracker.dontSkipUntilNextReload();\n _setReloadKey?.((currentKey) => currentKey + 1);\n });\n}\n\nif (isEditMode()) {\n const setupInitializer = () => {\n if (!isEmbeddedBySuperblocksFirstParty()) {\n return;\n }\n\n const handleInit: IframeEventHandler<\"sb-init\"> = async ({ data }) => {\n // Initialize tracer provider before WebSocket connection\n if (data.payload.windowOriginUrl) {\n initTracerProviderWithOrigin(data.payload.windowOriginUrl);\n }\n\n initializeEditStore();\n\n const editStore = getEditStore();\n editorBridge.connected();\n rootStore.setEditStore(editStore);\n rootStore.notifyEditorRegistered();\n\n // Initialize screenshot handler (only in edit mode)\n initializeScreenshotHandler();\n\n const { aiState, interactionMode } = data.payload;\n if (\n aiState?.generationState &&\n (aiState.generationState === AiGenerationState.GENERATING ||\n aiState.generationState === AiGenerationState.DEBUGGING)\n ) {\n editStore.ai.startEditing();\n if (aiState.editingComponents) {\n editStore.ai.setEditingComponents(aiState.editingComponents);\n }\n }\n\n if (interactionMode) {\n editStore.setInteractionMode(interactionMode);\n }\n\n if (\n data.payload.sessionRecordingKey &&\n data.payload.userId &&\n data.payload.appId\n ) {\n editStore.startRecording({\n userId: data.payload.userId,\n appId: data.payload.appId,\n sessionRecordingKey: data.payload.sessionRecordingKey,\n });\n }\n\n try {\n await sourceUpdateApi.connect({\n peerId: data.payload.peerId,\n userId: data.payload.userId,\n authorization: data.payload.devServerAuthorization,\n applicationId: data.payload.appId,\n traceContext: data.payload.traceContext,\n connectionType: data.payload.connectionType,\n connectionTarget: data.payload.connectionTarget,\n });\n } catch (error) {\n console.error(\n \"Error connecting to internal socket from library\",\n error,\n );\n // This will close the iframe\n editorBridge.socketError(\n \"Error connecting to the remote dev server, please refresh the page\",\n );\n return;\n }\n };\n const handleTokenUpdate: IframeEventHandler<\"sb-update-token\"> = ({\n data,\n }) => {\n const { authorization } = data.payload;\n console.log(\n \"Received sb-update-token message from iframe\",\n authorization?.substring(0, 20),\n );\n sourceUpdateApi.updateAuthorization(authorization);\n };\n\n iframeMessageHandler.addEventListener(\"sb-init\", handleInit);\n iframeMessageHandler.addEventListener(\"sb-update-token\", handleTokenUpdate);\n };\n requestIdleCallback(setupInitializer);\n}\n\nconst IframeConnected = observer(function IframeConnected(\n props: React.PropsWithChildren,\n) {\n const [reloadKey, setReloadKey] = useState(0);\n _setReloadKey = setReloadKey;\n useEffect(() => {\n editorBridge.sendReady();\n }, []);\n // for drag and drop\n useEffect(() => {\n const handleDragStart: IframeEventHandler<\"dragstart\"> = () => {\n // TODO: implement drag start\n };\n iframeMessageHandler.addEventListener(\"dragstart\", handleDragStart);\n return () => {\n iframeMessageHandler.removeEventListener(\"dragstart\", handleDragStart);\n };\n }, []);\n\n // Console log capture and global error handlers\n useEffect(() => {\n if (!isEmbeddedBySuperblocksFirstParty()) {\n return;\n }\n\n // Store original console methods\n const originalConsole = {\n warn: console.warn,\n error: console.error,\n debug: console.debug,\n info: console.info,\n log: console.log,\n };\n\n // Debouncing: batch logs and send at most once per 100ms\n const pendingLogs: Array<{\n level: \"log\" | \"warn\" | \"error\" | \"info\" | \"debug\";\n args: any[];\n stack?: string;\n }> = [];\n let flushTimer: NodeJS.Timeout | null = null;\n\n // Efficient serialization with length limiting\n const serializeArg = (arg: any, maxLength = 5000): string => {\n if (arg === null) return \"null\";\n if (arg === undefined) return \"undefined\";\n\n const type = typeof arg;\n if (type === \"string\") return arg;\n if (type === \"number\" || type === \"boolean\") return String(arg);\n if (type === \"function\") return `[Function: ${arg.name || \"anonymous\"}]`;\n if (type === \"symbol\") return arg.toString();\n\n // For objects, use JSON.stringify with special type handling\n try {\n const result = JSON.stringify(arg, (_key, value) => {\n // Handle special types\n if (value instanceof Error) {\n return `Error: ${value.message}`;\n }\n if (value instanceof Date) {\n return value.toISOString();\n }\n if (value instanceof RegExp) {\n return value.toString();\n }\n if (typeof value === \"function\") {\n return `[Function: ${value.name || \"anonymous\"}]`;\n }\n return value;\n });\n\n // Truncate if too long\n if (result.length > maxLength) {\n return result.substring(0, maxLength) + \"... [truncated]\";\n }\n return result;\n } catch {\n return \"[Circular or non-serializable object]\";\n }\n };\n\n // Check if a stack trace indicates framework code\n const isFrameworkStack = (stack: string | undefined): boolean => {\n if (!stack) return false;\n\n const frameworkStackPatterns = [\n /\\/node_modules\\//i, // All npm dependencies\n /\\/packages\\/library\\//i, // All internal Superblocks library code\n ];\n\n const frames = stack\n .split(\"\\n\")\n .map((line) => line.trim())\n .filter(Boolean);\n\n if (frames.length === 0) {\n return false;\n }\n\n const isFrameworkFrame = (frame: string) =>\n frameworkStackPatterns.some((pattern) => pattern.test(frame));\n\n // Only treat the stack as framework-only if every frame matches the framework patterns.\n return frames.every(isFrameworkFrame);\n };\n\n // Patterns for framework/internal logs that should be filtered out\n const isFrameworkLog = (\n message: string,\n stack: string | undefined,\n ): boolean => {\n const frameworkPatterns = [\n /^\\[vite\\]/i, // Vite HMR logs\n /^Pinged library socket/i, // Internal socket pings\n /^\\[HMR\\]/i, // Hot module reload\n /^Download the React DevTools/i, // React DevTools spam\n /^\\[internal\\]/i, // Internal logs\n ];\n\n // Check message patterns\n if (frameworkPatterns.some((pattern) => pattern.test(message))) {\n return true;\n }\n\n // Check stack trace patterns\n return isFrameworkStack(stack);\n };\n\n const flushLogs = () => {\n if (pendingLogs.length === 0) return;\n\n const logsToSend = pendingLogs.splice(0); // Clear and get all pending\n flushTimer = null;\n\n logsToSend.forEach(({ level, args, stack }) => {\n try {\n // Serialize arguments efficiently\n const message = args.map(serializeArg).join(\" \");\n\n // Skip framework/internal logs (using both message and stack)\n if (isFrameworkLog(message, stack)) {\n return;\n }\n\n const logEntry = {\n id: generateId(),\n timestamp: Date.now(),\n level,\n message,\n stack,\n };\n\n // Send to AI service - server handles buffering\n editorBridge.sendConsoleLog(logEntry);\n } catch {\n // Silently fail to avoid infinite loops\n }\n });\n };\n\n const queueConsoleLog = (\n level: \"warn\" | \"error\" | \"debug\" | \"info\" | \"log\",\n args: any[],\n ) => {\n // Capture stack immediately to enable filtering\n let stack: string | undefined;\n const rawStack = new Error().stack;\n if (rawStack) {\n // Strip first 3 frames: Error line, queueConsoleLog, console.X\n const lines = rawStack.split(\"\\n\");\n stack = lines.length > 3 ? lines.slice(3).join(\"\\n\") : undefined;\n }\n\n pendingLogs.push({ level, args, stack });\n\n // Schedule flush if not already scheduled\n if (!flushTimer) {\n flushTimer = setTimeout(flushLogs, 100);\n }\n };\n\n // Monkey-patch console methods\n console.warn = (...args: any[]) => {\n originalConsole.warn(...args);\n queueConsoleLog(\"warn\", args);\n };\n\n console.error = (...args: any[]) => {\n originalConsole.error(...args);\n queueConsoleLog(\"error\", args);\n };\n\n console.debug = (...args: any[]) => {\n originalConsole.debug(...args);\n queueConsoleLog(\"debug\", args);\n };\n\n console.info = (...args: any[]) => {\n originalConsole.info(...args);\n queueConsoleLog(\"info\", args);\n };\n\n console.log = (...args: any[]) => {\n originalConsole.log(...args);\n queueConsoleLog(\"log\", args);\n };\n\n // Helper to safely serialize errors\n const serializeError = (error: any): string => {\n if (!error) return \"Unknown error\";\n\n // If it's already a string, return it\n if (typeof error === \"string\") return error;\n\n // Try .toString() first (works for Error objects)\n const strValue = error.toString?.();\n if (strValue && strValue !== \"[object Object]\") {\n return strValue;\n }\n\n // Fall back to JSON.stringify for plain objects\n try {\n return JSON.stringify(error);\n } catch {\n return String(error);\n }\n };\n\n // Global error handler for unhandled errors\n const handleGlobalError = (event: ErrorEvent) => {\n const errorData = {\n id: generateId(),\n timestamp: Date.now(),\n error: serializeError(event.error) || event.message,\n errorInfo: {\n componentStack: event.error?.stack || \"\",\n },\n identifier: undefined,\n };\n\n // Fallback if store not ready - log to console\n if (!rootStore.editStore?.ai) {\n originalConsole.error(\n \"[Lost runtime error - store not ready]\",\n errorData,\n );\n return;\n }\n\n rootStore.editStore.ai.handleRuntimeError(errorData);\n };\n\n // Global handler for unhandled promise rejections\n const handleUnhandledRejection = (event: PromiseRejectionEvent) => {\n const errorData = {\n id: generateId(),\n timestamp: Date.now(),\n error: serializeError(event.reason) || \"Unhandled promise rejection\",\n errorInfo: {\n componentStack: event.reason?.stack || \"\",\n },\n identifier: undefined,\n };\n\n // Fallback if store not ready - log to console\n if (!rootStore.editStore?.ai) {\n originalConsole.error(\n \"[Lost runtime error - store not ready]\",\n errorData,\n );\n return;\n }\n\n rootStore.editStore.ai.handleRuntimeError(errorData);\n };\n\n window.addEventListener(\"error\", handleGlobalError);\n window.addEventListener(\"unhandledrejection\", handleUnhandledRejection);\n\n // Cleanup\n return () => {\n // Clear any pending flush timer\n if (flushTimer) {\n clearTimeout(flushTimer);\n }\n\n // Restore console methods\n console.warn = originalConsole.warn;\n console.error = originalConsole.error;\n console.debug = originalConsole.debug;\n console.info = originalConsole.info;\n console.log = originalConsole.log;\n\n // Remove event listeners\n window.removeEventListener(\"error\", handleGlobalError);\n window.removeEventListener(\n \"unhandledrejection\",\n handleUnhandledRejection,\n );\n };\n }, []);\n\n // This is not a production-ready hack because it prevents all embedding\n const isPossiblyEditor = useMemo(isEmbeddedBySuperblocksFirstParty, []);\n\n const connectionStatus =\n rootStore.editStore?.connectionManager.connectionStatus;\n if (connectionStatus === \"pre-init\" || connectionStatus === \"connecting\") {\n return <FullPageSpinner />;\n }\n\n if (\n isPossiblyEditor &&\n rootStore.editStore?.isInitialized &&\n typeof window !== \"undefined\"\n ) {\n return <React.Fragment key={reloadKey}>{props.children}</React.Fragment>;\n }\n\n if (isEditMode()) {\n console.log(\"In edit mode, but editor has not initialized yet\");\n return null;\n }\n\n return <React.Fragment key={reloadKey}>{props.children}</React.Fragment>;\n});\n\nconst WithUserWrapper = (props: React.PropsWithChildren) => {\n const { data: currentUser, isLoading } = useGetCurrentUserQuery();\n\n if (isLoading) {\n return <FullPageSpinner />;\n }\n\n if (!currentUser) {\n return <div>No user found</div>;\n }\n\n return <>{props.children}</>;\n};\n\nconst Auth0Wrapper = (props: React.PropsWithChildren) => {\n return (\n <WithUserWrapper>\n <IframeConnected>{props.children}</IframeConnected>\n </WithUserWrapper>\n );\n};\n\nconst EmbedWrapper = (props: React.PropsWithChildren) => {\n const isRetrievingToken = useRef(false);\n const [error, setError] = useState<string | undefined>();\n const [isLoaded, setIsLoaded] = useState(false);\n\n const navigate = useNavigate();\n const superblocksContext = useSuperblocksContext();\n\n useEffect(() => {\n const maxRetries = 20;\n let retryCount = 0;\n let timeout: NodeJS.Timeout;\n\n const attemptBootstrap = () => {\n if (rootStore.apis.isInitialized()) {\n return;\n }\n\n if (retryCount < maxRetries) {\n retryCount++;\n\n window.parent.postMessage(\n {\n type: \"sb-editor-request-bootstrap\",\n },\n \"*\",\n );\n\n timeout = setTimeout(attemptBootstrap, 200);\n } else {\n setError(\"Token took too long to load after multiple retries\");\n }\n };\n\n timeout = setTimeout(attemptBootstrap, 200);\n return () => clearTimeout(timeout);\n }, []);\n\n useEffect(() => {\n const bootstrapResponseListener: IframeEventHandler<\n \"sb-bootstrap-response\"\n > = (event) => {\n try {\n handleBootstrapResponse(event);\n setIsLoaded(true);\n iframeMessageHandler.removeEventListener(\n \"sb-bootstrap-response\",\n bootstrapResponseListener,\n );\n } catch (e) {\n setError(e?.toString());\n }\n };\n iframeMessageHandler.addEventListener(\n \"sb-bootstrap-response\",\n bootstrapResponseListener,\n );\n\n const updateActiveAgentsListener: IframeEventHandler<\n \"sb-update-active-agents\"\n > = (event) => {\n rootStore.apis.agentUrls = event.data.payload.agentUrls;\n };\n iframeMessageHandler.addEventListener(\n \"sb-update-active-agents\",\n updateActiveAgentsListener,\n );\n\n const retrievePropertyPanelPropsListener: IframeEventHandler<\n \"sb-retrieve-property-panel-props\"\n > = (event) => {\n const sourceId = event.data.payload.sourceId as SbElement;\n\n const selectorIds =\n getEditStore().ui.getMostRelevantSelectorIdsForSourceId(sourceId);\n\n if (!sourceId || selectorIds.length === 0) {\n getEditStore().ui.setSelectedSourceIds([]);\n getEditStore().ui.setSelectedSelectorIds([]);\n getEditStore().ui.setFocusedIds(null);\n return;\n }\n\n const alreadySelected = getEditStore().ui.isSourceSelected(sourceId);\n if (!alreadySelected) {\n getEditStore().ui.setSelectedSourceIds([sourceId]);\n getEditStore().ui.setSelectedSelectorIds(Array.from(selectorIds));\n getEditStore().ui.setFocusedIds(Array.from(selectorIds)[0]);\n }\n getEditStore().propertiesPanelManager.trackPropertiesPanel(\n selectorIds[0],\n );\n };\n iframeMessageHandler.addEventListener(\n \"sb-retrieve-property-panel-props\",\n retrievePropertyPanelPropsListener,\n );\n\n const editOperationAcknowledgeListener: IframeEventHandler<\n \"sb-edit-operation-acknowledge\"\n > = (event) => {\n getEditStore().operationManager.acknowledgeEditOperation(\n event.data.payload,\n );\n };\n iframeMessageHandler.addEventListener(\n \"sb-edit-operation-acknowledge\",\n editOperationAcknowledgeListener,\n );\n\n const updatePropertyWithEffectsListener: IframeEventHandler<\n \"sb-update-property-with-effects\"\n > = (event) => {\n const payload = {\n sourceId: event.data.payload.sourceId as SbElement,\n updates: event.data.payload.updates,\n };\n const propUpdates =\n getEditStore().propertiesPanelManager.computeAndApplySideEffectsForPropertyUpdate(\n payload,\n );\n\n editorBridge.resolvePromise(event.data.payload.callbackId, propUpdates);\n editorBridge.resolvePromise(\n event.data.payload.callbackId,\n payload.updates,\n );\n\n Object.keys(propUpdates).forEach((sourceId) => {\n getEditStore().operationManager.writeRuntimeProperties(\n sourceId as SbElement,\n event.data.payload.transaction.id,\n propUpdates[sourceId as SbElement],\n );\n });\n getEditStore().operationManager.writeRuntimeProperties(\n payload.sourceId,\n event.data.payload.transaction.id,\n payload.updates,\n );\n };\n iframeMessageHandler.addEventListener(\n \"sb-update-property-with-effects\",\n updatePropertyWithEffectsListener,\n );\n\n const createComponentListener: IframeEventHandler<\n \"sb-create-component\"\n > = async (event) => {\n const {\n componentType,\n parent,\n scopeName,\n baseProperties,\n skipSecondaryComponentsCreation,\n otherComponentsUpdates,\n } = event.data.payload;\n\n try {\n await createComponent({\n componentType,\n parent,\n scopeName,\n baseProperties,\n skipSecondaryComponentsCreation,\n otherComponentsUpdates,\n });\n } catch (error) {\n console.error(\"Failed to create component:\", error);\n }\n };\n iframeMessageHandler.addEventListener(\n \"sb-create-component\",\n createComponentListener,\n );\n\n const setInteractionModeListener: IframeEventHandler<\n \"set-interaction-mode\"\n > = async (event) => {\n const { interactionMode } = event.data.payload;\n rootStore.editStore?.setInteractionMode(interactionMode);\n };\n iframeMessageHandler.addEventListener(\n \"set-interaction-mode\",\n setInteractionModeListener,\n );\n\n const globalSyncListener: IframeEventHandler<\"sb-global-sync\"> = (\n event,\n ) => {\n const { global } = event.data.payload;\n superblocksContext.updateContext(global);\n };\n iframeMessageHandler.addEventListener(\"sb-global-sync\", globalSyncListener);\n\n const navigateToListener: IframeEventHandler<\"route-change\"> = async (\n event,\n ) => {\n const { route, routeParams, queryParams } = event.data.payload;\n\n const eventSearch = new URLSearchParams(queryParams);\n const nextSearch = new URLSearchParams(window.location.search);\n\n for (const [key, value] of eventSearch.entries()) {\n nextSearch.set(key, value);\n }\n\n await navigate({\n pathname: generatePath(route, routeParams),\n search: nextSearch.toString(),\n });\n };\n iframeMessageHandler.addEventListener(\"route-change\", navigateToListener);\n\n const aiUpdatesListener: IframeEventHandler<\"ai-updates\"> = (event) => {\n const { type } = event.data.payload;\n switch (type) {\n case \"start-editing\": {\n getEditStore().ai.startEditing();\n if (event.data.payload.components) {\n getEditStore().ai.setEditingComponents(\n event.data.payload.components,\n );\n }\n break;\n }\n case \"update-editing-entities\": {\n getEditStore().ai.setEditingComponents(event.data.payload.components);\n break;\n }\n case \"finish-editing\": {\n getEditStore().ai.finishEditing();\n break;\n }\n case \"set-ai-context-mode\": {\n const { mode, components } = event.data.payload;\n getEditStore().ai.setAiContextMode(mode, components);\n break;\n }\n case \"set-tagging-enabled\": {\n const { isTaggingEnabled } = event.data.payload;\n getEditStore().ai.setIsTaggingEnabled(isTaggingEnabled);\n break;\n }\n }\n };\n\n iframeMessageHandler.addEventListener(\"ai-updates\", aiUpdatesListener);\n\n const hmrReloadListener: IframeEventHandler<\"hmr-reload-request\"> = () => {\n triggerHmrReload(true);\n };\n\n iframeMessageHandler.addEventListener(\n \"hmr-reload-request\",\n hmrReloadListener,\n );\n\n return () => {\n iframeMessageHandler.removeEventListener(\n \"sb-bootstrap-response\",\n bootstrapResponseListener,\n );\n iframeMessageHandler.removeEventListener(\n \"sb-update-active-agents\",\n updateActiveAgentsListener,\n );\n iframeMessageHandler.removeEventListener(\n \"sb-edit-operation-acknowledge\",\n editOperationAcknowledgeListener,\n );\n iframeMessageHandler.removeEventListener(\n \"sb-update-property-with-effects\",\n updatePropertyWithEffectsListener,\n );\n iframeMessageHandler.removeEventListener(\n \"sb-retrieve-property-panel-props\",\n retrievePropertyPanelPropsListener,\n );\n iframeMessageHandler.removeEventListener(\n \"sb-create-component\",\n createComponentListener,\n );\n iframeMessageHandler.removeEventListener(\n \"sb-global-sync\",\n globalSyncListener,\n );\n iframeMessageHandler.removeEventListener(\n \"route-change\",\n navigateToListener,\n );\n iframeMessageHandler.removeEventListener(\"ai-updates\", aiUpdatesListener);\n iframeMessageHandler.removeEventListener(\n \"hmr-reload-request\",\n hmrReloadListener,\n );\n\n // Clear all runtime subscriptions on cleanup\n try {\n const editStore = getEditStore();\n editStore.runtimeSubscriptionsStore.clearAll();\n } catch {\n // EditStore might not be initialized yet\n }\n };\n }, [navigate, superblocksContext]);\n\n useEffect(() => {\n const messageListener = (event: MessageEvent) => {\n if (event.data?.type === \"parent-action-batch\" && event.data.payload) {\n event.data.payload.forEach((action: MessageAction) => {\n // TODO(code-mode): we ideally have a way to share this payload type from the editor, or\n // the editor should be able to import this type from the library\n switch (action.type) {\n case \"operations/editor:selectWidgets\": {\n const sourceIds: SbElement[] = action.payload.sourceIds;\n const selectorIdHint = action.payload.selectorIdHint;\n\n getEditStore().ui.setSelectedSourceIds(sourceIds);\n\n const selectorIds = sourceIds\n .flatMap((sourceId) => {\n // If we have a selectorIdHint and it matches this sourceId, use it\n if (selectorIdHint) {\n const component =\n getEditStore().runtimeTrackingStore.getComponent(\n selectorIdHint as SbSelector,\n );\n if (component?.sourceId === sourceId) {\n return [selectorIdHint as SbSelector];\n }\n }\n // Otherwise, use the default logic\n return getEditStore().ui.getMostRelevantSelectorIdsForSourceId(\n sourceId,\n );\n })\n .filter((selectorId) => selectorId !== null);\n getEditStore().ui.setSelectedSelectorIds(selectorIds);\n break;\n }\n case \"codeMode/cancelApiExecution\": {\n const { apiId } = action.payload;\n rootStore.apis.cancelApi(apiId);\n break;\n }\n case \"RUN_API\": {\n const { apiName, traceHeaders, callId, isTestRun, inputs } =\n action.payload;\n\n console.log(\"[iframe-wrappers] Received RUN_API:\", {\n apiName,\n callId,\n isTestRun,\n hasInputs: !!inputs,\n inputs,\n traceHeaders,\n });\n\n if (isTestRun) {\n console.log(\"[iframe-wrappers] Running as test run\");\n rootStore.apis\n .runApiByPath({\n path: getApiPath(apiName as never),\n inputs: { ...traceHeaders, ...inputs },\n isTestRun: true,\n })\n .catch((error) => {\n console.error(`Failed to test API ${apiName}:`, error);\n });\n } else if (callId) {\n console.log(\n \"[iframe-wrappers] Re-running with callId:\",\n callId,\n );\n // If callId is provided, this is a re-run request\n rootStore.apis.rerunApiByCallId(callId).catch((error) => {\n console.error(\n `Failed to re-run API with callId ${callId}:`,\n error,\n );\n });\n } else {\n console.log(\n \"[iframe-wrappers] This might be a Clark request - executing API normally\",\n );\n\n // Execute the API normally for Clark requests\n rootStore.apis\n .runApiByPath({\n path: getApiPath(apiName as never),\n inputs: { ...traceHeaders, ...inputs },\n callId,\n isTestRun: false,\n })\n .catch((error) => {\n console.error(`Failed to run API ${apiName}:`, error);\n });\n }\n\n break;\n }\n }\n });\n }\n };\n\n window.addEventListener(\"message\", messageListener);\n return () => window.removeEventListener(\"message\", messageListener);\n }, []);\n\n /**\n * This effect registers a listener that's called by the Vite dev server\n * after creating a new page. This helps us avoid race conditions by first\n * waiting for the page to be fully loaded and registered in the router\n * before attempting to navigate to it.\n * */\n const location = useLocation();\n useEffect(() => {\n try {\n const editStore = getEditStore();\n return editStore.onViteMessage(\n ViteMessageKind.ROUTE_CHANGE,\n async (message) => {\n try {\n const { route, routeTestParams } = message;\n const path = generatePath(route, routeTestParams);\n await navigate({ pathname: path, search: location.search });\n } catch (error) {\n throw new Error(`Failed to navigate to route: ${error}`);\n }\n },\n );\n } catch {\n return;\n }\n }, [navigate, location, isLoaded]);\n\n if (!isLoaded && error) {\n return (\n <div>\n <h3>There was an error logging in to Superblocks.</h3>\n <p>{error}</p>\n </div>\n );\n }\n\n if (!rootStore.apis.isInitialized() && !isLoaded) {\n if (!isRetrievingToken.current && window.parent !== window.self) {\n window.parent.postMessage(\n {\n type: \"sb-editor-request-bootstrap\",\n },\n \"*\",\n );\n isRetrievingToken.current = true;\n }\n\n return <FullPageSpinner />;\n }\n\n return (\n <WithUserWrapper>\n <IframeConnected>\n <BuildErrorNotification />\n <EditorHotkeys>{props.children}</EditorHotkeys>\n </IframeConnected>\n </WithUserWrapper>\n );\n};\n\nexport { EmbedWrapper, Auth0Wrapper };\n","export function throttle<T extends (...args: any[]) => any>(\n func: T,\n delay: number,\n): ((...args: Parameters<T>) => void) & { cancel: () => void } {\n let timeoutId: ReturnType<typeof setTimeout>;\n let lastExecTime = 0;\n\n const throttled = function (this: any, ...args: Parameters<T>) {\n const currentTime = Date.now();\n\n if (currentTime - lastExecTime < delay) {\n clearTimeout(timeoutId);\n timeoutId = setTimeout(() => {\n lastExecTime = currentTime;\n func.apply(this, args);\n }, delay);\n } else {\n lastExecTime = currentTime;\n func.apply(this, args);\n }\n };\n\n throttled.cancel = () => {\n clearTimeout(timeoutId);\n };\n\n return throttled;\n}\n\nexport function debounce<T extends (...args: any[]) => any>(\n func: T,\n delay: number,\n): (...args: Parameters<T>) => void {\n let timeoutId: ReturnType<typeof setTimeout>;\n\n return function (this: any, ...args: Parameters<T>) {\n clearTimeout(timeoutId);\n timeoutId = setTimeout(() => {\n func.apply(this, args);\n }, delay);\n };\n}\n","export const EXTENDED_CLICKABLE_AREA_DELTA = 6;\n\nexport const EXTENDED_CLICKABLE_ANCHOR_CSS = {\n top: `calc(anchor(top) - ${EXTENDED_CLICKABLE_AREA_DELTA}px)`,\n left: `calc(anchor(left) - ${EXTENDED_CLICKABLE_AREA_DELTA}px)`,\n right: `calc(anchor(right) - ${EXTENDED_CLICKABLE_AREA_DELTA}px)`,\n bottom: `calc(anchor(bottom) - ${EXTENDED_CLICKABLE_AREA_DELTA}px)`,\n};\n\nexport const EXTENDED_CLICKABLE_ANCHOR_CLIP_PATH = `polygon(\n 0% 0%, 0% 100%, 100% 100%, 100% 0%,\n 0% 0%, ${EXTENDED_CLICKABLE_AREA_DELTA}px ${EXTENDED_CLICKABLE_AREA_DELTA}px, calc(100% - ${EXTENDED_CLICKABLE_AREA_DELTA}px) ${EXTENDED_CLICKABLE_AREA_DELTA}px, \n calc(100% - ${EXTENDED_CLICKABLE_AREA_DELTA}px) calc(100% - ${EXTENDED_CLICKABLE_AREA_DELTA}px), ${EXTENDED_CLICKABLE_AREA_DELTA}px calc(100% - ${EXTENDED_CLICKABLE_AREA_DELTA}px), ${EXTENDED_CLICKABLE_AREA_DELTA}px ${EXTENDED_CLICKABLE_AREA_DELTA}px\n )`;\n","import {\n NO_SELECT_ATTRIBUTE,\n SELECTOR_ID_ATTRIBUTE,\n} from \"@superblocksteam/library-shared\";\nimport rootStore from \"../../lib/internal-details/lib/root-store.js\";\nimport { EXTENDED_CLICKABLE_AREA_DELTA } from \"../extended-clickable-area.js\";\nimport { getEditStore } from \"../get-edit-store.js\";\nimport type { SbSelector } from \"@superblocksteam/library-shared/types\";\n\nconst enablePointerEventsOnDisabledElements = (\n rootElement: HTMLElement | null,\n): (() => void) => {\n const editStore = getEditStore();\n const disabledSelectorIds =\n editStore.runtimeTrackingStore.getDisabledComponents();\n const modifiedElements: Array<{\n element: HTMLElement;\n hadInlineStyle: boolean;\n originalValue: string;\n }> = [];\n\n for (const selectorId of disabledSelectorIds) {\n const renderedTag =\n editStore.runtimeTrackingStore.getFirstAnchorableTag(selectorId);\n const selectorToQuery = renderedTag ?? selectorId;\n\n const element = document.querySelector(\n `[${SELECTOR_ID_ATTRIBUTE}=\"${selectorToQuery}\"]`,\n ) as HTMLElement | null;\n\n if (element) {\n if (!rootElement || rootElement.contains(element)) {\n const computedPointerEvents = getComputedStyle(element).pointerEvents;\n\n if (computedPointerEvents !== \"auto\") {\n const hadInlineStyle = element.style.pointerEvents !== \"\";\n const originalValue = element.style.pointerEvents;\n\n modifiedElements.push({\n element,\n hadInlineStyle,\n originalValue,\n });\n\n element.style.pointerEvents = \"auto\";\n }\n }\n }\n }\n\n return () => {\n modifiedElements.forEach(({ element, hadInlineStyle, originalValue }) => {\n if (hadInlineStyle) {\n element.style.pointerEvents = originalValue;\n } else {\n element.style.removeProperty(\"pointer-events\");\n }\n });\n };\n};\n\nconst calculateWidgetsAtCursor = (params: {\n x: number;\n y: number;\n rootElement: HTMLElement | null;\n delta?: { x: number; y: number };\n}) => {\n const restorePointerEvents = enablePointerEventsOnDisabledElements(\n params.rootElement,\n );\n\n try {\n let elements = document.elementsFromPoint(params.x, params.y);\n if (params.delta) {\n elements = [\n ...document.elementsFromPoint(\n params.x - params.delta.x,\n params.y - params.delta.y,\n ),\n ...document.elementsFromPoint(\n params.x + params.delta.x,\n params.y + params.delta.y,\n ),\n ...document.elementsFromPoint(\n params.x - params.delta.x,\n params.y + params.delta.y,\n ),\n ...document.elementsFromPoint(\n params.x + params.delta.x,\n params.y - params.delta.y,\n ),\n ];\n }\n const hoveredPills: { selectorId: SbSelector; noSelect?: boolean }[] = [];\n const hoveredActual: { selectorId: SbSelector; noSelect?: boolean }[] = [];\n\n new Set(elements).forEach((element) => {\n if (params.rootElement && !params.rootElement.contains(element)) {\n return; // Skip elements not within the rootElement\n }\n\n const selectorIdFromActual = element.getAttribute(SELECTOR_ID_ATTRIBUTE);\n if (selectorIdFromActual) {\n hoveredActual.push({\n selectorId: selectorIdFromActual as SbSelector,\n noSelect: element.hasAttribute(NO_SELECT_ATTRIBUTE),\n });\n } else {\n const selectorIdFromPill = element.getAttribute(\n \"data-sb-actions-selector-id\",\n );\n if (selectorIdFromPill) {\n hoveredPills.push({\n selectorId: selectorIdFromPill as SbSelector,\n });\n }\n }\n });\n\n return {\n hoveredPills,\n hoveredActual,\n };\n } finally {\n restorePointerEvents();\n }\n};\n\nconst getFirstItemWithFocusedSelectorPrioritized = (\n widgets: Array<{ selectorId: SbSelector; noSelect?: boolean }>,\n): { selectorId: SbSelector; noSelect?: boolean } | undefined => {\n const focusedSelectorId = getEditStore().ui.getFocusedSelectorId();\n if (focusedSelectorId) {\n const focusedPill = widgets.find((item) => {\n return item.selectorId === focusedSelectorId;\n });\n if (focusedPill) {\n return focusedPill;\n }\n }\n return widgets[0];\n};\n\n/*\n * First try to find a widget with an extended click area (only select if the widget has extended click area configured)\n * Then try to find a widget at the exact cursor position\n * Prioritize name pills over the underlying component\n */\nconst getWidgetFromPointHelper = (params: {\n x: number;\n y: number;\n rootElement: HTMLElement | null;\n}): { selectorId: SbSelector; noSelect?: boolean } | undefined => {\n const { x, y, rootElement } = params;\n const widgetsWithBuffer = calculateWidgetsAtCursor({\n x,\n y,\n rootElement,\n delta: {\n x: EXTENDED_CLICKABLE_AREA_DELTA,\n y: EXTENDED_CLICKABLE_AREA_DELTA,\n },\n });\n\n if (widgetsWithBuffer.hoveredPills.length > 0) {\n return getFirstItemWithFocusedSelectorPrioritized(\n widgetsWithBuffer.hoveredPills,\n );\n }\n\n const editStore = getEditStore();\n const extendedWidget = widgetsWithBuffer.hoveredActual.find((item) => {\n let actualSelectorId: SbSelector | undefined = item.selectorId;\n if (item.noSelect) {\n actualSelectorId =\n editStore.runtimeTrackingStore.getNearestSelectableAncestor(\n item.selectorId,\n false,\n );\n if (!actualSelectorId) {\n return false;\n }\n }\n const componentType =\n editStore.runtimeTrackingStore.getComponent(actualSelectorId)?.type;\n const editorConfig =\n rootStore.componentRegistry.getEditorConfigFromComponentType(\n componentType,\n );\n return editorConfig?.hasExtendedClickArea;\n });\n\n if (extendedWidget) {\n return extendedWidget;\n }\n\n const atPointWidgets = calculateWidgetsAtCursor({\n x,\n y,\n rootElement,\n });\n\n const firstWidget =\n getFirstItemWithFocusedSelectorPrioritized(atPointWidgets.hoveredPills) ??\n atPointWidgets.hoveredActual[0];\n\n return firstWidget;\n};\n\nconst shouldBubbleUpForNearestSelectableAncestor = (selectorId: SbSelector) => {\n const editStore = getEditStore();\n const widgetNode = editStore.runtimeTrackingStore.getComponent(selectorId);\n\n // New behavior: don't bubble based on noSelect anymore - we handle firstRenderedTag logic elsewhere\n // Only bubble if the widget itself is marked as an internal Superblocks component that shouldn't be directly selected\n const parentSelectorId =\n editStore.runtimeTrackingStore.getComponentParent(selectorId);\n if (!parentSelectorId) {\n return false;\n }\n const parentNode =\n editStore.runtimeTrackingStore.getComponent(parentSelectorId);\n\n // Only bubble if parent is an internal Superblocks component (not user-registered)\n // and current node is also an internal component\n return parentNode?.isSbComponent && widgetNode?.isSbComponent;\n};\n\n/**\n * This function will only return a new selector ID if and only if:\n * - The given instance represents a source ID with more than 1 instance on the page.\n * - The parent instance represents a source ID with FEWER instances than the given instance.\n * - The parent instance only contains 1 child (the given instance)\n *\n * Essentially, this should only ever \"narrow\" down the selection.\n * This is designed for situations where the user clicks on an HTML element that is heavily reused.\n * Example: components with some common styling.\n */\nconst getRelevantParentIfItReducesRepetition = (selectorId: SbSelector) => {\n const editStore = getEditStore();\n const component = editStore.runtimeTrackingStore.getComponent(selectorId);\n if (!component) {\n return undefined;\n }\n const allSelectorIdsForSourceId =\n editStore.runtimeTrackingStore.getSelectorIdsForSourceId(\n component.sourceId,\n );\n if (allSelectorIdsForSourceId.size <= 1) {\n return undefined;\n }\n const parentSelectorId =\n editStore.runtimeTrackingStore.getComponentParent(selectorId);\n const parentComponent = parentSelectorId\n ? editStore.runtimeTrackingStore.getComponent(parentSelectorId)\n : undefined;\n if (\n !parentComponent ||\n editStore.runtimeTrackingStore.getComponentChildren(parentSelectorId)\n .length !== 1\n ) {\n return undefined;\n }\n const parentSelectorIdsForSourceId =\n editStore.runtimeTrackingStore.getSelectorIdsForSourceId(\n parentComponent.sourceId,\n );\n if (parentSelectorIdsForSourceId.size < allSelectorIdsForSourceId.size) {\n return parentSelectorId;\n }\n return undefined;\n};\n\n/*\n * New selection algorithm:\n * 1. If the clicked element has data-no-select, bubble up to nearest selectable ancestor\n * 2. If the clicked element is the firstRenderedTag of a registered component, select that component\n * 3. Otherwise, select the HTML element itself (applying repetition reduction if helpful)\n * 4. Only bubble up for internal Superblocks components that shouldn't be directly selected\n */\nexport function getMostRelevantWidgetAtPoint(params: {\n x: number;\n y: number;\n rootElement: HTMLElement | null;\n}): SbSelector | undefined {\n const widget = getWidgetFromPointHelper(params);\n if (!widget) {\n return undefined;\n }\n const editStore = getEditStore();\n\n // If this element has data-no-select, bubble up to nearest selectable ancestor\n if (widget.noSelect) {\n const selectableAncestor =\n editStore.runtimeTrackingStore.getNearestSelectableAncestor(\n widget.selectorId,\n true, // skip self since self has no-select\n );\n if (selectableAncestor) {\n return selectableAncestor;\n }\n // If no selectable ancestor found, fall through to default behavior\n }\n\n // Check if this element is the root DOM element of a registered component\n // If so, select the outermost such component\n const componentForFirstRenderedTag =\n editStore.runtimeTrackingStore.getOutermostComponentForFirstRenderedTag(\n widget.selectorId,\n );\n if (componentForFirstRenderedTag) {\n return componentForFirstRenderedTag;\n }\n\n // If not the root of a registered component, try to reduce repetition for raw HTML elements\n const relevantParent = getRelevantParentIfItReducesRepetition(\n widget.selectorId,\n );\n if (relevantParent) {\n return relevantParent;\n }\n\n // Check if we need to bubble up for internal Superblocks components\n // IMPORTANT: Only bubble for non-HTML elements (internal Superblocks components)\n // HTML elements should always be selectable directly\n const widgetNode = editStore.runtimeTrackingStore.getComponent(\n widget.selectorId,\n );\n const isHtmlElement = widgetNode?.isHtmlElement;\n\n if (!isHtmlElement) {\n const bubbleUp = shouldBubbleUpForNearestSelectableAncestor(\n widget.selectorId,\n );\n if (bubbleUp) {\n const registeredAncestor =\n editStore.runtimeTrackingStore.getNearestSelectableAncestor(\n widget.selectorId,\n false,\n );\n if (registeredAncestor) {\n return registeredAncestor;\n }\n }\n }\n\n // Default: select the element itself\n return widget.selectorId;\n}\n","import { SELECTOR_ID_ATTRIBUTE } from \"@superblocksteam/library-shared\";\nimport { AiContextMode } from \"@superblocksteam/library-shared/types\";\nimport { observer } from \"mobx-react-lite\";\nimport React, { useCallback, useEffect, useState } from \"react\";\nimport ReactDOM from \"react-dom\";\nimport rootStore from \"../../lib/internal-details/lib/root-store.js\";\nimport { throttle } from \"../../lib/internal-details/lib/throttle.js\";\nimport { getEditStore } from \"../get-edit-store.js\";\nimport { editorBridge } from \"../superblocks-editor-bridge.js\";\nimport { getMostRelevantWidgetAtPoint } from \"./get-widgets-from-point.js\";\nimport {\n InteractionRect,\n selectDisplayNameAndVisibility,\n type SelectionInfo,\n useSelectionElements,\n} from \"./interaction-rect.jsx\";\n\nexport type RootType = \"App\" | \"Page\" | string;\n\nconst INTERACTION_LAYER_ATTRIBUTE = \"data-interaction-layer\";\n/**\n * Check if an element is an interaction layer container.\n */\nfunction isInteractionLayerContainer(element: Node): boolean {\n return (\n element instanceof HTMLElement &&\n element.getAttribute(INTERACTION_LAYER_ATTRIBUTE) === \"true\"\n );\n}\n\n/**\n * Get all direct children of body, excluding interaction layer containers.\n */\nfunction getBodyChildren(): HTMLElement[] {\n if (!document.body) {\n return [];\n }\n return Array.from(document.body.children).filter(\n (child) => !isInteractionLayerContainer(child),\n ) as HTMLElement[];\n}\n\n/**\n * Find the highest ancestor of an element that is a direct child of body.\n * Returns null if element is not in the document or has no body-child ancestor.\n */\nfunction getBodyChildAncestor(element: HTMLElement | null): HTMLElement | null {\n if (!element || !document.body) {\n return null;\n }\n\n let current: HTMLElement | null = element;\n while (current && current.parentElement !== document.body) {\n current = current.parentElement;\n }\n\n return current;\n}\n\n/**\n * Filter selection elements to only those that belong to the given container.\n * An element belongs to a container if its highest body-child ancestor matches the container.\n */\nfunction getElementsInScope(\n containerElement: HTMLElement,\n allElements: SelectionInfo[],\n editStore: ReturnType<typeof getEditStore>,\n): SelectionInfo[] {\n return allElements.filter((info) => {\n // Get the rendered tag for this selector\n const renderedTag = editStore.runtimeTrackingStore.getFirstAnchorableTag(\n info.selectorId,\n );\n const selectorToQuery = renderedTag ?? info.selectorId;\n\n // Find the DOM element\n const element = document.querySelector(\n `[${SELECTOR_ID_ATTRIBUTE}=\"${selectorToQuery}\"]`,\n ) as HTMLElement | null;\n\n if (!element) {\n return false;\n }\n\n // Find the highest body-child ancestor of this element\n const bodyChildAncestor = getBodyChildAncestor(element);\n\n // Element belongs to this container if its body-child ancestor matches\n return bodyChildAncestor === containerElement;\n });\n}\n\nfunction useWidgetHover() {\n const editStore = getEditStore();\n const interactionMode = editStore.interactionMode;\n const aiContextMode = editStore.ai.getAiContextMode();\n\n useEffect(() => {\n // Only enable hover in design mode or target mode (AUTO_SELECT)\n const isDesignMode = interactionMode === \"design\";\n const isTargetMode = aiContextMode === AiContextMode.AUTO_SELECT;\n\n if (!isDesignMode && !isTargetMode) {\n return;\n }\n\n const rootElement = document.body;\n const handleMouseMove = (event: MouseEvent) => {\n const selectorId = getMostRelevantWidgetAtPoint({\n x: event.clientX,\n y: event.clientY,\n rootElement,\n });\n if (selectorId) {\n editStore.ui.setFocusedIds(selectorId);\n }\n };\n\n const throttledHandleMouseMove = throttle(handleMouseMove, 25);\n const handleMouseLeave = () => {\n throttledHandleMouseMove.cancel();\n editStore.ui.setFocusedIds(null);\n };\n\n rootElement?.addEventListener(\"mousemove\", throttledHandleMouseMove);\n rootElement?.addEventListener(\"mouseleave\", handleMouseLeave);\n\n return () => {\n rootElement?.removeEventListener(\"mousemove\", throttledHandleMouseMove);\n rootElement?.removeEventListener(\"mouseleave\", handleMouseLeave);\n };\n }, [interactionMode, aiContextMode, editStore.ui]);\n}\n\nfunction useWidgetClick() {\n useEffect(() => {\n const rootElement = document.body;\n const editStore = getEditStore();\n\n const isInsideInteractionLayer = (element: EventTarget | null) => {\n if (!(element instanceof Element)) {\n return false;\n }\n return (\n element.closest(`[${INTERACTION_LAYER_ATTRIBUTE}=\"true\"]`) !== null\n );\n };\n\n const handleClick = (event: MouseEvent) => {\n if (event.defaultPrevented) {\n return;\n }\n\n if (!rootElement) {\n return;\n }\n\n // Don't handle clicks on interaction layer elements (name pills, action buttons)\n // Let them handle their own clicks\n if (isInsideInteractionLayer(event.target)) {\n return;\n }\n\n const selectorId = getMostRelevantWidgetAtPoint({\n x: event.clientX,\n y: event.clientY,\n rootElement,\n });\n if (!selectorId) {\n return;\n }\n\n // Get component info\n const component = editStore.runtimeTrackingStore.getComponent(selectorId);\n if (!component) {\n console.log(\n \"[internal] [useWidgetClick] No component found for selectorId\",\n );\n return;\n }\n\n const sourceId = component.sourceId;\n const { displayName } = selectDisplayNameAndVisibility(selectorId);\n\n const isTargettingComponent =\n editStore.ai.shouldToggleComponentInAiContext() || event.altKey;\n\n // do not propagate the click event when in design or target mode\n if (editStore.interactionMode === \"design\" || isTargettingComponent) {\n event.preventDefault();\n event.stopPropagation();\n }\n\n // Handle Alt key or AI tagging mode\n if (isTargettingComponent) {\n console.log(\n \"[internal] [useWidgetClick] Toggling component in AI context\",\n );\n editorBridge.toggleComponentInAiContext(\n sourceId,\n selectorId,\n displayName,\n );\n return;\n }\n editStore.ui.selectWidget(selectorId, event.shiftKey === true);\n };\n\n const handlePointerDown = (event: PointerEvent) => {\n const isTargetMode = editStore.ai.shouldToggleComponentInAiContext();\n\n if (\n (editStore.interactionMode === \"design\" || isTargetMode) &&\n !isInsideInteractionLayer(event.target)\n ) {\n event.preventDefault();\n event.stopPropagation();\n }\n };\n\n rootElement?.addEventListener(\"click\", handleClick, {\n capture: true,\n });\n rootElement?.addEventListener(\"pointerdown\", handlePointerDown, {\n capture: true,\n });\n\n return () => {\n rootElement?.removeEventListener(\"click\", handleClick, {\n capture: true,\n });\n rootElement?.removeEventListener(\"pointerdown\", handlePointerDown, {\n capture: true,\n });\n };\n }, []);\n}\n\ninterface InteractionLayerProps {\n containerElement: HTMLElement;\n layerId: string;\n}\n\nconst InteractionLayer = observer(\n ({ containerElement, layerId }: InteractionLayerProps) => {\n const editStore = getEditStore();\n const interactionMode = editStore.interactionMode;\n const allSelectedElements = useSelectionElements({\n focusedSourceId: editStore.ui.getFocusedSourceId(),\n focusedSelectorId: editStore.ui.getFocusedSelectorId(),\n selectedSelectorIds: editStore.ui.getSelectedSelectorIds(),\n selectedSourceIds: editStore.ui.getSelectedSourceIds(),\n targetedSourceIds: editStore.ai.getTargetedComponents(),\n aiContextMode: editStore.ai.getAiContextMode(),\n interactionMode,\n });\n\n // Filter elements to only those in this layer's scope\n const selectedElementsInScope = React.useMemo(\n () =>\n getElementsInScope(containerElement, allSelectedElements, editStore),\n [containerElement, allSelectedElements, editStore],\n );\n\n const isAiEditing = editStore.ai.getIsEditing();\n if (isAiEditing) {\n return null;\n }\n\n // Render interaction rects for elements in scope\n const interactionRectsForSelectedElements = selectedElementsInScope.map(\n (info, index) => {\n return (\n <InteractionRect\n key={info.selectorId + info.selectionType + index}\n {...info}\n />\n );\n },\n );\n\n // Create portal container and position it right after the container element\n const [portalContainer, setPortalContainer] =\n React.useState<HTMLElement | null>(null);\n\n useEffect(() => {\n const container = document.createElement(\"div\");\n container.className = `interaction-layer-container interaction-layer-${layerId}`;\n container.setAttribute(INTERACTION_LAYER_ATTRIBUTE, \"true\");\n container.style.cssText =\n \"position: fixed; overflow: hidden; z-index: 50; width: 0; height: 0; top: 0; left: 0;\";\n\n // Insert the portal container right after the container element\n const nextSibling = containerElement.nextSibling;\n if (nextSibling) {\n document.body.insertBefore(container, nextSibling);\n } else {\n document.body.appendChild(container);\n }\n\n setPortalContainer(container);\n\n return () => {\n container.remove();\n setPortalContainer(null);\n };\n }, [containerElement, layerId, editStore.interactionMode]);\n\n if (!portalContainer) {\n return null;\n }\n\n return ReactDOM.createPortal(\n <div\n style={\n interactionMode === \"design\"\n ? { \"--primary-rect-color\": \"#0BAD5C\" }\n : { \"--primary-rect-color\": \"#0087E0\" }\n }\n >\n {interactionRectsForSelectedElements}\n </div>,\n portalContainer,\n );\n },\n);\n\nconst InteractionLayerManager = observer(() => {\n useWidgetHover();\n useWidgetClick();\n\n const editStore = getEditStore();\n\n const handleCanvasClick = useCallback(() => {\n editorBridge.canvasClicked();\n }, []);\n\n useEffect(() => {\n window.addEventListener(\"click\", handleCanvasClick, true);\n return () => {\n window.removeEventListener(\"click\", handleCanvasClick, true);\n };\n }, [handleCanvasClick]);\n\n // Track all direct children of body (excluding interaction layer containers)\n const [bodyChildren, setBodyChildren] = useState<HTMLElement[]>(() => {\n return getBodyChildren();\n });\n\n // Observe body children changes\n useEffect(() => {\n if (!document.body) {\n return;\n }\n\n const updateBodyChildren = () => {\n setBodyChildren(getBodyChildren());\n };\n\n // Initial update\n updateBodyChildren();\n\n // Set up MutationObserver to watch for changes\n const observer = new MutationObserver((mutations) => {\n // Only update if the mutation is not from an interaction layer container being added/removed\n for (const mutation of mutations) {\n if (mutation.type === \"childList\") {\n const addedNodes = Array.from(mutation.addedNodes);\n const removedNodes = Array.from(mutation.removedNodes);\n const isInteractionLayerChange =\n addedNodes.some(isInteractionLayerContainer) ||\n removedNodes.some(isInteractionLayerContainer);\n\n // Only update if the change is not from our interaction layers\n if (!isInteractionLayerChange) {\n updateBodyChildren();\n break;\n }\n }\n }\n });\n\n observer.observe(document.body, { childList: true });\n\n return () => {\n observer.disconnect();\n };\n }, []);\n\n const isAiEditing = editStore.ai.getIsEditing();\n if (isAiEditing) {\n return null;\n }\n\n // Render one InteractionLayer for each body child\n return (\n <>\n {bodyChildren.map((child, index) => {\n const layerId = `layer-${index}-${child.tagName.toLowerCase()}`;\n return (\n <InteractionLayer\n key={layerId}\n containerElement={child}\n layerId={layerId}\n />\n );\n })}\n </>\n );\n});\n\n// Always-on context menu handler - runs even when interaction layer is not visible\nfunction useGlobalContextMenu() {\n useEffect(() => {\n const rootElement = document.body;\n\n const handleContextMenu = (event: MouseEvent) => {\n if (event.defaultPrevented) {\n return;\n }\n\n if (!rootElement) {\n return;\n }\n\n // Get fresh state from editStore\n const editStore = getEditStore();\n const isTargetMode = editStore.ai.shouldToggleComponentInAiContext();\n\n // Only show context menu when NOT in target mode\n if (isTargetMode) {\n return;\n }\n\n const selectorId = getMostRelevantWidgetAtPoint({\n x: event.clientX,\n y: event.clientY,\n rootElement,\n });\n\n if (!selectorId) {\n return;\n }\n\n const component = editStore.runtimeTrackingStore.getComponent(selectorId);\n if (!component) {\n return;\n }\n\n const sourceId = component.sourceId;\n\n event.preventDefault();\n event.stopPropagation();\n\n editorBridge.registerContextMenuClick(\n sourceId,\n selectorId,\n event.clientX,\n event.clientY,\n );\n };\n\n rootElement?.addEventListener(\"contextmenu\", handleContextMenu, {\n capture: true,\n });\n\n return () => {\n rootElement?.removeEventListener(\"contextmenu\", handleContextMenu, {\n capture: true,\n });\n };\n }, []);\n}\n\nconst ExternalInteractionLayer = observer(() => {\n const isEditStoreInitialized = Boolean(rootStore.editStore?.isInitialized);\n\n // Always run context menu handler, even when interaction layer is not visible\n useGlobalContextMenu();\n\n const isDesignMode = rootStore.editStore?.interactionMode === \"design\";\n const isTargetMode =\n rootStore.editStore?.ai.shouldToggleComponentInAiContext();\n const aiContextMode = rootStore.editStore?.ai.getAiContextMode();\n const isHighlightMode = aiContextMode === AiContextMode.HIGHLIGHT;\n\n // Also show interaction layer when there's a selected widget (for context menu)\n const hasSelectedWidget =\n (rootStore.editStore?.ui.getSelectedSourceIds().length ?? 0) > 0;\n\n // Show interaction layers in design mode, target mode, highlight mode, or when widget is selected\n const interactionLayerVisible =\n isDesignMode || isTargetMode || isHighlightMode || hasSelectedWidget;\n const shouldShowInteractionLayers =\n isEditStoreInitialized && interactionLayerVisible;\n if (!shouldShowInteractionLayers) {\n return null;\n }\n\n const pencilCursor = `url('data:image/svg+xml;utf8,<svg width=\"16\" height=\"16\" viewBox=\"0 0 16 16\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\"><path opacity=\"0.12\" d=\"M11.8703 5.81338C10.8293 5.47941 10.0738 4.50819 10.0626 3.35904L10.7109 2.71072C11.4229 1.99876 12.5772 1.99877 13.2892 2.71075C14.0011 3.42272 14.0011 4.57702 13.2892 5.28897L13.2083 5.36988C12.8412 5.73698 12.3436 5.9652 11.8703 5.81338Z\" fill=\"black\" stroke=\"black\" stroke-width=\"0.125\"/><path d=\"M10.0001 3.33308L4.18981 9.14329C3.6314 9.7017 3.25077 10.4129 3.0959 11.1873L2.66675 13.333L4.8125 12.9039C5.58686 12.749 6.29806 12.3684 6.85646 11.81L12.6667 5.99967M10.0001 3.33308L10.6668 2.66633C11.4032 1.92996 12.5971 1.92997 13.3335 2.66636V2.66636C14.0698 3.40273 14.0698 4.59661 13.3335 5.33297L12.6667 5.99967M10.0001 3.33308C10.0001 4.8058 11.194 5.99967 12.6667 5.99967\" stroke=\"white\" stroke-width=\"2.5\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/><path d=\"M10.0001 3.33308L4.18981 9.14329C3.6314 9.7017 3.25077 10.4129 3.0959 11.1873L2.66675 13.333L4.8125 12.9039C5.58686 12.749 6.29806 12.3684 6.85646 11.81L12.6667 5.99967M10.0001 3.33308L10.6668 2.66633C11.4032 1.92996 12.5971 1.92997 13.3335 2.66636V2.66636C14.0698 3.40273 14.0698 4.59661 13.3335 5.33297L12.6667 5.99967M10.0001 3.33308C10.0001 4.8058 11.194 5.99967 12.6667 5.99967\" stroke=\"black\" stroke-width=\"1.25\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/></svg>') 0 16, auto`;\n const targetCursor = `url('data:image/svg+xml;utf8,<svg width=\"16\" height=\"16\" viewBox=\"0 0 16 16\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\"><path opacity=\"0.12\" fill-rule=\"evenodd\" clip-rule=\"evenodd\" d=\"M14 8C14 11.3137 11.3137 14 8 14C4.68629 14 2 11.3137 2 8C2 4.68629 4.68629 2 8 2C11.3137 2 14 4.68629 14 8ZM8 9.26316C8.69762 9.26316 9.26316 8.69762 9.26316 8C9.26316 7.30238 8.69762 6.73684 8 6.73684C7.30238 6.73684 6.73684 7.30238 6.73684 8C6.73684 8.69762 7.30238 9.26316 8 9.26316Z\" fill=\"black\"/><path d=\"M14 8C14 11.3137 11.3137 14 8 14M14 8C14 4.68629 11.3137 2 8 2M14 8H12M8 14C4.68629 14 2 11.3137 2 8M8 14V12M2 8C2 4.68629 4.68629 2 8 2M2 8H4M8 2V4M9.26316 8C9.26316 8.69762 8.69762 9.26316 8 9.26316C7.30238 9.26316 6.73684 8.69762 6.73684 8C6.73684 7.30238 7.30238 6.73684 8 6.73684C8.69762 6.73684 9.26316 7.30238 9.26316 8Z\" stroke=\"white\" stroke-width=\"2.5\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/><path d=\"M14 8C14 11.3137 11.3137 14 8 14M14 8C14 4.68629 11.3137 2 8 2M14 8H12M8 14C4.68629 14 2 11.3137 2 8M8 14V12M2 8C2 4.68629 4.68629 2 8 2M2 8H4M8 2V4M9.26316 8C9.26316 8.69762 8.69762 9.26316 8 9.26316C7.30238 9.26316 6.73684 8.69762 6.73684 8C6.73684 7.30238 7.30238 6.73684 8 6.73684C8.69762 6.73684 9.26316 7.30238 9.26316 8Z\" stroke=\"black\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/></svg>') 8 8, auto`;\n\n let cursorStyle = \"\";\n if (isTargetMode) {\n cursorStyle = `* { cursor: ${targetCursor} !important; }`;\n } else if (isDesignMode) {\n cursorStyle = `* { cursor: ${pencilCursor} !important; }`;\n }\n\n return (\n <>\n <InteractionLayerManager />\n {cursorStyle && (\n <style\n dangerouslySetInnerHTML={{\n __html: cursorStyle,\n }}\n ></style>\n )}\n </>\n );\n});\n\nexport default ExternalInteractionLayer;\n","import React, { useEffect, useRef, useState } from \"react\";\nimport { generatePath, useNavigate } from \"react-router\";\nimport { handleBootstrapResponse } from \"./handle-bootstrap-response.js\";\nimport { FullPageSpinner } from \"./internal-components/spinner.jsx\";\nimport { useGetCurrentUserQuery } from \"./lib/features/injected-features.js\";\nimport { iframeMessageHandler } from \"./lib/iframe.js\";\nimport rootStore from \"./lib/root-store.js\";\nimport { useSuperblocksContext } from \"./superblocks-context.js\";\nimport type { IframeEventHandler } from \"./lib/iframe.js\";\nimport type { MessageAction } from \"../user-facing/types.js\";\n\nconst WithUserWrapper = (props: React.PropsWithChildren) => {\n const { data: currentUser, isLoading } = useGetCurrentUserQuery();\n\n if (isLoading) {\n return <FullPageSpinner />;\n }\n\n if (!currentUser) {\n return <div>No user found</div>;\n }\n\n return <>{props.children}</>;\n};\n\nconst Auth0Wrapper = (props: React.PropsWithChildren) => {\n return <WithUserWrapper>{props.children}</WithUserWrapper>;\n};\n\nconst EmbedWrapper = (props: React.PropsWithChildren) => {\n const isRetrievingToken = useRef(false);\n const [error, setError] = useState<string | undefined>();\n const [isLoaded, setIsLoaded] = useState(false);\n const navigate = useNavigate();\n const superblocksContext = useSuperblocksContext();\n\n useEffect(() => {\n const maxRetries = 20;\n let retryCount = 0;\n let timeout: NodeJS.Timeout;\n\n const attemptBootstrap = () => {\n if (rootStore.apis.isInitialized()) {\n return;\n }\n\n if (retryCount < maxRetries) {\n retryCount++;\n\n window.parent.postMessage(\n {\n type: \"sb-editor-request-bootstrap\",\n },\n \"*\",\n );\n\n timeout = setTimeout(attemptBootstrap, 200);\n } else {\n setError(\"Token took too long to load after multiple retries\");\n }\n };\n\n timeout = setTimeout(attemptBootstrap, 200);\n return () => clearTimeout(timeout);\n }, []);\n\n useEffect(() => {\n const bootstrapResponseListener: IframeEventHandler<\n \"sb-bootstrap-response\"\n > = (event) => {\n try {\n handleBootstrapResponse(event);\n setIsLoaded(true);\n iframeMessageHandler.removeEventListener(\n \"sb-bootstrap-response\",\n bootstrapResponseListener,\n );\n } catch (e) {\n setError(e?.toString());\n }\n };\n iframeMessageHandler.addEventListener(\n \"sb-bootstrap-response\",\n bootstrapResponseListener,\n );\n\n const globalSyncListener: IframeEventHandler<\"sb-global-sync\"> = (\n event,\n ) => {\n const { global } = event.data.payload;\n superblocksContext.updateContext(global);\n };\n iframeMessageHandler.addEventListener(\"sb-global-sync\", globalSyncListener);\n\n const navigateToListener: IframeEventHandler<\"route-change\"> = async (\n event,\n ) => {\n const { route, routeParams, queryParams } = event.data.payload;\n\n const eventSearch = new URLSearchParams(queryParams);\n const nextSearch = new URLSearchParams(window.location.search);\n\n for (const [key, value] of eventSearch.entries()) {\n nextSearch.set(key, value);\n }\n\n await navigate({\n pathname: generatePath(route, routeParams),\n search: nextSearch.toString(),\n });\n };\n iframeMessageHandler.addEventListener(\"route-change\", navigateToListener);\n\n return () => {\n iframeMessageHandler.removeEventListener(\n \"sb-bootstrap-response\",\n bootstrapResponseListener,\n );\n iframeMessageHandler.removeEventListener(\n \"sb-global-sync\",\n globalSyncListener,\n );\n iframeMessageHandler.removeEventListener(\n \"route-change\",\n navigateToListener,\n );\n };\n }, [navigate, superblocksContext]);\n\n useEffect(() => {\n const messageListener = (event: MessageEvent) => {\n if (event.data?.type === \"parent-action-batch\" && event.data.payload) {\n event.data.payload.forEach((action: MessageAction) => {\n // TODO(code-mode): we ideally have a way to share this payload type from the editor, or\n // the editor should be able to import this type from the library\n switch (action.type) {\n case \"RUN_API\": {\n // TODO: entityManager has been removed. API execution should now\n // go through rootStore.apis.runApiByPath or another method\n console.warn(\n \"RUN_API action is not supported without entityManager\",\n );\n break;\n }\n }\n });\n }\n };\n\n window.addEventListener(\"message\", messageListener);\n return () => window.removeEventListener(\"message\", messageListener);\n }, []);\n\n if (!isLoaded && error) {\n return (\n <div>\n <h3>There was an error logging in to Superblocks.</h3>\n <p>{error}</p>\n </div>\n );\n }\n\n if (!rootStore.apis.isInitialized() && !isLoaded) {\n if (!isRetrievingToken.current && window.parent !== window.self) {\n window.parent.postMessage(\n {\n type: \"sb-editor-request-bootstrap\",\n },\n \"*\",\n );\n isRetrievingToken.current = true;\n }\n\n return <FullPageSpinner />;\n }\n\n return <WithUserWrapper>{props.children}</WithUserWrapper>;\n};\n\nexport { EmbedWrapper, Auth0Wrapper };\n","import { Observer } from \"mobx-react-lite\";\nimport React from \"react\";\nimport { editorBridge } from \"../../../../edit-mode/superblocks-editor-bridge.js\";\nimport { isEditMode } from \"../../is-edit-mode.js\";\nimport rootStore from \"../../lib/root-store.js\";\nimport {\n ErrorIconContainer,\n StyledClarkIcon,\n ErrorTitle,\n ErrorMessage,\n ErrorDetails,\n ErrorSummary,\n ErrorStack,\n ErrorContainer,\n ErrorContent,\n SecondaryButton,\n ActionsContainer,\n} from \"../common.js\";\nimport { FixWithClarkButton } from \"../fix-with-clark-button.jsx\";\nimport type { LibUserAccessibleTheme } from \"../../../user-facing/themes/types.js\";\n\ninterface ErrorBoundaryState {\n hasError: boolean;\n error?: Error;\n}\n\ninterface ErrorBoundaryProps {\n children: React.ReactNode;\n theme?: LibUserAccessibleTheme;\n}\n\nexport class InternalErrorBoundary extends React.Component<\n ErrorBoundaryProps,\n ErrorBoundaryState\n> {\n constructor(props: ErrorBoundaryProps) {\n super(props);\n this.state = { hasError: false };\n }\n\n static getDerivedStateFromError(e: Error): ErrorBoundaryState {\n const error =\n e instanceof Error\n ? e\n : new Error(\n typeof e === \"object\" && e !== null ? JSON.stringify(e) : String(e),\n );\n return { hasError: true, error };\n }\n\n componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {\n console.error(\"Superblocks application error:\", error, errorInfo);\n if (isEditMode()) {\n editorBridge.sendLoadError(String(error));\n }\n }\n\n handleRefresh = () => {\n window.location.reload();\n };\n\n render() {\n if (this.state.hasError) {\n return (\n <Observer>\n {() => {\n // Check if AI is currently generating\n const isAIGenerating =\n rootStore.editStore?.ai.getIsEditing() ?? false;\n\n if (isAIGenerating) {\n // During AI generation, don't show error UI\n // Children already crashed, so just render nothing\n return null;\n }\n\n // When AI is not generating, show full error UI\n return (\n <ErrorContainer>\n <ErrorContent>\n <ErrorIconContainer>\n <StyledClarkIcon />\n </ErrorIconContainer>\n\n <ErrorTitle>Something went wrong</ErrorTitle>\n <ErrorMessage>\n {this.state.error?.message || \"Unknown error\"}\n </ErrorMessage>\n\n <ActionsContainer>\n {isEditMode() && (\n <FixWithClarkButton error={this.state.error} />\n )}\n <SecondaryButton onClick={this.handleRefresh}>\n Refresh page\n </SecondaryButton>\n </ActionsContainer>\n\n {this.state.error && (\n <ErrorDetails>\n <ErrorSummary>Full details</ErrorSummary>\n <ErrorStack>{this.state.error.stack}</ErrorStack>\n </ErrorDetails>\n )}\n </ErrorContent>\n </ErrorContainer>\n );\n }}\n </Observer>\n );\n }\n\n return this.props.children;\n }\n}\n","import React, { Suspense } from \"react\";\n\nlet internalStores: Record<string, any> = {};\n\nconst SUPPORTED_MODES = [\"local-dev\"];\n\nfunction registerStores(stores: Record<string, any>) {\n internalStores = { ...internalStores, ...stores };\n\n if (SUPPORTED_MODES.includes(import.meta.env.MODE)) {\n if (Object.keys(internalStores).length === Object.keys(stores).length) {\n import(\"./devtools-consolidated.jsx\")\n .then(({ initializeCustomDevTools, setRegisteredStores }) => {\n setRegisteredStores(internalStores);\n initializeCustomDevTools();\n })\n .catch((error) => {\n console.warn(\n \"[DevTools] Failed to initialize custom devtools:\",\n error,\n );\n });\n }\n }\n}\n\nconst DevToolsInternal = React.lazy(() => {\n return import(\"./devtools-consolidated.jsx\").then((module) => ({\n default: module.CustomDevTools,\n }));\n});\n\nconst DevTools = () => {\n if (!SUPPORTED_MODES.includes(import.meta.env.MODE)) {\n return null;\n }\n\n return (\n <Suspense fallback={null}>\n <DevToolsInternal />\n </Suspense>\n );\n};\n\nexport { DevTools, registerStores };\n","import equal from \"@superblocksteam/fast-deep-equal/es6\";\nimport { useContext, useEffect, useMemo, useRef } from \"react\";\nimport {\n UNSAFE_DataRouterContext,\n useLocation,\n useParams,\n type Location,\n} from \"react-router\";\nimport rootStore from \"./lib/root-store.js\";\n\nexport function useTrackRouteChange() {\n const routerContext = useContext(UNSAFE_DataRouterContext);\n const location = useLocation();\n const params = useParams();\n const prevLocation = useRef<Location>();\n\n const routes = useMemo(() => {\n if (!routerContext?.router.routes) return [];\n return routerContext?.router.routes;\n }, [routerContext?.router.routes]);\n\n useEffect(() => {\n if (!equal(location, prevLocation.current)) {\n rootStore.locationStore?.updateLocation(location, routes, params);\n // TODO: how do we decouple this routing change from the widget selection?\n rootStore.editStore?.ui.selectWidget(null);\n prevLocation.current = location;\n }\n }, [location, routes, params]);\n}\n","import { editorBridge } from \"../../edit-mode/superblocks-editor-bridge.js\";\nimport { isEditMode } from \"../internal-details/is-edit-mode.js\";\nimport rootStore from \"../internal-details/lib/root-store.js\";\n\nlet sbProviderRendered = false;\n\nexport const reportSbProviderRenderedEditMode = () => {\n sbProviderRendered = true;\n};\n\nconst ERROR_ID = \"base-app-not-rendered\";\n\nif (isEditMode()) {\n setTimeout(() => {\n if (!rootStore.editStore) {\n console.error(\"Edit store not initialized.\");\n }\n\n if (sbProviderRendered) {\n // in case this was fixed without us noticing it\n editorBridge.sendClearRuntimeError(ERROR_ID, true);\n return;\n }\n\n const errorMessage = `AppProvider not rendered in time.\nPlease ensure that 'App' from @superblocksteam/library is always rendered.\nAPI executions and editor features will be unavailable.\n`;\n console.error(errorMessage);\n editorBridge.sendRuntimeError(\n {\n id: ERROR_ID,\n error: errorMessage,\n errorInfo: {},\n },\n true,\n );\n editorBridge.sendLoadError(errorMessage);\n const intervalId = setInterval(() => {\n if (sbProviderRendered) {\n clearInterval(intervalId);\n editorBridge.sendClearRuntimeError(ERROR_ID, true);\n return;\n }\n }, 1000);\n }, 10_000);\n}\n","import { compile, middleware, prefixer, serialize, stringify } from \"stylis\";\n\nexport const VARIABLES: Record<string, string> = {\n primaryColor: \"--primary-color\",\n};\n\nconst VARIABLE_VALUES: Record<keyof typeof VARIABLES, string> = {\n primaryColor: \"blue\",\n};\n\nlet componentVariables: Record<string, string> = {};\nlet componentVariableValues: Record<string, string> = {};\n\nconst createStyleSheetFromString = (sheetId: string, styleSheet: string) => {\n const styles = serialize(\n compile(styleSheet),\n middleware([prefixer, stringify]),\n );\n const existingStyleTag = document.getElementById(sheetId);\n const styleTag = existingStyleTag ?? document.createElement(\"style\");\n styleTag.setAttribute(\"id\", sheetId);\n styleTag.replaceChildren(document.createTextNode(styles));\n if (existingStyleTag) return;\n document.head.appendChild(styleTag);\n};\n\nconst registry: Record<string, string> = {};\nexport const registerComponentStyle = (\n componentName: string,\n styleSheet: string,\n variableDefns: Record<string, string>,\n variableValues: Record<string, string>,\n) => {\n componentVariables = { ...componentVariables, ...variableDefns };\n componentVariableValues = { ...componentVariableValues, ...variableValues };\n const sheetId = `${componentName}-styles`;\n registry[sheetId] = styleSheet;\n};\n\nexport const initializeStyles = (appName: string) => {\n const stylesheet = Object.entries(registry)\n .map(([, styleSheet]) => styleSheet)\n .join(\"\\n\");\n const allVariables = { ...VARIABLES, ...componentVariables };\n const allVariableValues = { ...VARIABLE_VALUES, ...componentVariableValues };\n const variableDefns = Object.keys(allVariables)\n .map(\n (variable) =>\n `${allVariables[variable]}: ${allVariableValues[variable]};`,\n )\n .join(\"\\n\");\n createStyleSheetFromString(\n appName,\n `:${appName} {${variableDefns}}\\n${stylesheet}`,\n );\n};\n\nexport const MIN_EMPTY_WIDGET_SIZE = \"15px\";\n","import { getBindingIdentifier } from \"@superblocksteam/library-shared\";\nimport React, { useEffect, useState } from \"react\";\nimport {\n Auth0Wrapper as EditorAuth0Wrapper,\n EmbedWrapper as EditorEmbedWrapper,\n} from \"../../edit-mode/iframe-wrappers.jsx\";\nimport InteractionLayer from \"../../edit-mode/interaction-layer/interaction-layer.js\";\nimport {\n Auth0Wrapper as AppAuth0Wrapper,\n EmbedWrapper as AppEmbedWrapper,\n} from \"../internal-details/app-wrappers.jsx\";\nimport { InternalErrorBoundary } from \"../internal-details/internal-components/error-boundary/index.jsx\";\nimport { FullPageSpinner } from \"../internal-details/internal-components/spinner.js\";\nimport { isEditMode } from \"../internal-details/is-edit-mode.js\";\nimport { DevTools } from \"../internal-details/lib/devtools/index.jsx\";\nimport {\n iframeMessageHandler,\n type IframeEventHandler,\n} from \"../internal-details/lib/iframe.js\";\nimport {\n rejectById,\n resolveById,\n} from \"../internal-details/lib/resolve-id-singleton.js\";\nimport rootStore from \"../internal-details/lib/root-store.js\";\nimport { useTrackRouteChange } from \"../internal-details/routing.js\";\nimport { SuperblocksContextProvider } from \"../internal-details/superblocks-context.js\";\nimport { initializeCSSVariables } from \"./properties-panel/mixins/extract-variables.js\";\nimport { reportSbProviderRenderedEditMode } from \"./sb-provider-tracker.js\";\nimport { initializeStyles } from \"./styling/styles.js\";\nimport type { SuperblocksAppContext } from \"../internal-details/superblocks-context.js\";\n\nconst originalLog = console.log;\n\nconsole.log = (...args) => {\n try {\n const processedArgs = args.map((arg) => {\n if (\n arg &&\n typeof arg === \"object\" &&\n (getBindingIdentifier(arg) || getBindingIdentifier(arg.bind ?? {}))\n ) {\n return JSON.parse(JSON.stringify(arg));\n }\n return arg;\n });\n originalLog(...processedArgs);\n } catch {\n // Do nothing\n }\n};\n\nconst loadApisIntoLibrary = async function loadApisIntoLibrary() {\n if (!isEditMode()) {\n try {\n const mod = await import(\"./build-manifest.js\");\n rootStore.apis.loadApiManifest(mod.default);\n } catch (error) {\n console.error(\"Error loading apis into library\", error);\n }\n }\n};\n\nconst Auth0Wrapper = isEditMode() ? EditorAuth0Wrapper : AppAuth0Wrapper;\nconst EmbedWrapper = isEditMode() ? EditorEmbedWrapper : AppEmbedWrapper;\n\nconst SbProvider = function SbProvider({\n name = \"codemode\",\n children,\n className,\n context,\n}: {\n name?: string;\n children?: React.ReactNode;\n className?: string;\n context?: SuperblocksAppContext;\n}) {\n const isEmbedded =\n typeof window !== \"undefined\" && window.parent !== window.self;\n\n useTrackRouteChange();\n\n const [isApisInitialized, setIsApisInitialized] = useState(false);\n useEffect(() => {\n (async () => {\n await loadApisIntoLibrary();\n setIsApisInitialized(true);\n })();\n }, []);\n\n useEffect(() => {\n const resolvePromiseListener: IframeEventHandler<\"resolve-promise\"> = (\n event,\n ) => {\n resolveById(event.data.callbackId, event.data.payload);\n };\n\n const rejectPromiseListener: IframeEventHandler<\"reject-promise\"> = (\n event,\n ) => {\n rejectById(event.data.callbackId, event.data.payload);\n };\n\n // These handlers need to be here instead of on the iframe wrappers because\n // we need the promise resolution on the API set before we render the iframe wrapper\n iframeMessageHandler.addEventListener(\n \"resolve-promise\",\n resolvePromiseListener,\n );\n iframeMessageHandler.addEventListener(\n \"reject-promise\",\n rejectPromiseListener,\n );\n return () => {\n iframeMessageHandler.removeEventListener(\n \"resolve-promise\",\n resolvePromiseListener,\n );\n iframeMessageHandler.removeEventListener(\n \"reject-promise\",\n rejectPromiseListener,\n );\n };\n }, []);\n\n useEffect(() => {\n initializeStyles(name);\n }, [name]);\n\n // if in edit mode, try to extract css variables and report that we're rendered\n useEffect(() => {\n if (isEditMode()) {\n initializeCSSVariables();\n reportSbProviderRenderedEditMode();\n }\n }, []);\n\n if (!isApisInitialized) {\n return <FullPageSpinner />;\n }\n\n return (\n <div id=\"sb-provider-root\" className={className}>\n <InternalErrorBoundary>\n <div className=\"h-full w-full relative\">\n <SuperblocksContextProvider value={context ?? undefined}>\n {isEmbedded ? (\n <EmbedWrapper>{children}</EmbedWrapper>\n ) : (\n <Auth0Wrapper>{children}</Auth0Wrapper>\n )}\n </SuperblocksContextProvider>\n <DevTools />\n </div>\n </InternalErrorBoundary>\n <InteractionLayer />\n </div>\n );\n};\n\nexport default SbProvider;\n","import type { EditorConfig } from \"@superblocksteam/library-shared/types\";\n\nexport const editorConfig: EditorConfig = {\n icon: \"app\",\n isDraggable: false,\n};\n","import { tailwindStylesCategory } from \"../../properties-panel/mixins/styles-category.js\";\nimport {\n Prop,\n PropsCategory,\n Section,\n} from \"../../properties-panel/props-builder.js\";\n\nexport const propertiesDefinition = {\n contents: Section.category(PropsCategory.Content).children({\n children: Prop.jsx(),\n }),\n appearance: tailwindStylesCategory(),\n};\n","import { NATIVE_COMPONENT_TYPES } from \"@superblocksteam/library-shared\";\nimport { observer } from \"mobx-react-lite\";\nimport { registerComponentInternal } from \"../../internal-index.js\";\nimport SuperblocksProvider from \"../../sb-provider.jsx\";\nimport { editorConfig } from \"./editor.js\";\nimport { propertiesDefinition } from \"./props.js\";\nimport type { SuperblocksAppContext } from \"../../../internal-details/superblocks-context.js\";\nimport type { InternalProps } from \"../../properties-panel/props-builder.js\";\n\nconst App = observer(\n ({\n children,\n className,\n context,\n }: InternalProps<typeof propertiesDefinition> & {\n context?: SuperblocksAppContext;\n }) => {\n return (\n <SuperblocksProvider name=\"App\" className={className} context={context}>\n {children}\n </SuperblocksProvider>\n );\n },\n);\nApp.displayName = NATIVE_COMPONENT_TYPES.App;\n\nregisterComponentInternal(App, propertiesDefinition).editorConfig(editorConfig);\n\nexport { App };\n","export enum API_STATUS_CODES {\n REQUEST_UNAUTHORIZED = 401,\n RESOURCE_FORBIDDEN = 403,\n RESOURCE_NOT_FOUND = 404,\n TIMEOUT = 408,\n RESOURCE_CONFLICT = 409,\n SERVER_ERROR = 502,\n SERVER_UNAVAILABLE = 503,\n BAD_REQUEST = 400,\n}\n","<svg width=\"167\" height=\"168\" viewBox=\"0 0 167 168\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\">\n<g filter=\"url(#filter0_i_1_117)\">\n<g clip-path=\"url(#clip0_1_117)\">\n<rect width=\"164\" height=\"164\" rx=\"82\" fill=\"#F9FAFB\"/>\n<g filter=\"url(#filter1_dd_1_117)\">\n<g clip-path=\"url(#clip1_1_117)\">\n<rect x=\"32\" y=\"36\" width=\"256\" height=\"140\" rx=\"6\" fill=\"white\"/>\n<rect width=\"132\" height=\"12\" transform=\"translate(32 36)\" fill=\"#454D5F\"/>\n<circle opacity=\"0.24\" cx=\"39\" cy=\"42\" r=\"3\" fill=\"white\"/>\n<rect opacity=\"0.24\" x=\"46\" y=\"41\" width=\"10\" height=\"2\" rx=\"1\" fill=\"white\"/>\n<rect x=\"44\" y=\"60\" width=\"104\" height=\"36\" rx=\"4\" fill=\"#F3F4F6\"/>\n<rect x=\"44\" y=\"104\" width=\"48\" height=\"36\" rx=\"4\" fill=\"#F3F4F6\"/>\n<rect x=\"44\" y=\"148\" width=\"48\" height=\"36\" rx=\"4\" fill=\"#F3F4F6\"/>\n<rect x=\"100\" y=\"104\" width=\"48\" height=\"36\" rx=\"4\" fill=\"#F3F4F6\"/>\n<rect x=\"100\" y=\"148\" width=\"48\" height=\"36\" rx=\"4\" fill=\"#F3F4F6\"/>\n</g>\n</g>\n</g>\n</g>\n<g filter=\"url(#filter2_d_1_117)\">\n<rect x=\"108\" y=\"108\" width=\"56\" height=\"56\" rx=\"28\" fill=\"white\" shape-rendering=\"crispEdges\"/>\n<circle cx=\"136\" cy=\"136\" r=\"23.5\" fill=\"#F9FAFB\" stroke=\"#C6CAD2\" stroke-dasharray=\"4 4\"/>\n<path opacity=\"0.2\" d=\"M143.5 132.25H128.5C128.086 132.25 127.75 132.586 127.75 133V143.5C127.75 143.914 128.086 144.25 128.5 144.25H143.5C143.914 144.25 144.25 143.914 144.25 143.5V133C144.25 132.586 143.914 132.25 143.5 132.25Z\" fill=\"#6C7689\"/>\n<path d=\"M143.5 132.25H128.5C128.086 132.25 127.75 132.586 127.75 133V143.5C127.75 143.914 128.086 144.25 128.5 144.25H143.5C143.914 144.25 144.25 143.914 144.25 143.5V133C144.25 132.586 143.914 132.25 143.5 132.25Z\" stroke=\"#6C7689\" stroke-width=\"1.25\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/>\n<path d=\"M132.625 132.25V128.875C132.625 127.98 132.981 127.121 133.614 126.489C134.246 125.856 135.105 125.5 136 125.5C136.895 125.5 137.754 125.856 138.386 126.489C139.019 127.121 139.375 127.98 139.375 128.875V132.25\" stroke=\"#6C7689\" stroke-width=\"1.25\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/>\n<path d=\"M136 139.375C136.621 139.375 137.125 138.871 137.125 138.25C137.125 137.629 136.621 137.125 136 137.125C135.379 137.125 134.875 137.629 134.875 138.25C134.875 138.871 135.379 139.375 136 139.375Z\" fill=\"#6C7689\"/>\n</g>\n<defs>\n<filter id=\"filter0_i_1_117\" x=\"0\" y=\"-1\" width=\"164\" height=\"165\" filterUnits=\"userSpaceOnUse\" color-interpolation-filters=\"sRGB\">\n<feFlood flood-opacity=\"0\" result=\"BackgroundImageFix\"/>\n<feBlend mode=\"normal\" in=\"SourceGraphic\" in2=\"BackgroundImageFix\" result=\"shape\"/>\n<feColorMatrix in=\"SourceAlpha\" type=\"matrix\" values=\"0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0\" result=\"hardAlpha\"/>\n<feOffset dy=\"-1\"/>\n<feGaussianBlur stdDeviation=\"1.5\"/>\n<feComposite in2=\"hardAlpha\" operator=\"arithmetic\" k2=\"-1\" k3=\"1\"/>\n<feColorMatrix type=\"matrix\" values=\"0 0 0 0 0.1056 0 0 0 0 0.11904 0 0 0 0 0.1344 0 0 0 0.2 0\"/>\n<feBlend mode=\"normal\" in2=\"shape\" result=\"effect1_innerShadow_1_117\"/>\n</filter>\n<filter id=\"filter1_dd_1_117\" x=\"29\" y=\"34\" width=\"262\" height=\"146\" filterUnits=\"userSpaceOnUse\" color-interpolation-filters=\"sRGB\">\n<feFlood flood-opacity=\"0\" result=\"BackgroundImageFix\"/>\n<feColorMatrix in=\"SourceAlpha\" type=\"matrix\" values=\"0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0\" result=\"hardAlpha\"/>\n<feOffset/>\n<feGaussianBlur stdDeviation=\"1\"/>\n<feComposite in2=\"hardAlpha\" operator=\"out\"/>\n<feColorMatrix type=\"matrix\" values=\"0 0 0 0 0.0775545 0 0 0 0 0.0335371 0 0 0 0 0.206463 0 0 0 0.12 0\"/>\n<feBlend mode=\"normal\" in2=\"BackgroundImageFix\" result=\"effect1_dropShadow_1_117\"/>\n<feColorMatrix in=\"SourceAlpha\" type=\"matrix\" values=\"0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0\" result=\"hardAlpha\"/>\n<feOffset dy=\"1\"/>\n<feGaussianBlur stdDeviation=\"1.5\"/>\n<feComposite in2=\"hardAlpha\" operator=\"out\"/>\n<feColorMatrix type=\"matrix\" values=\"0 0 0 0 0.0775545 0 0 0 0 0.0335371 0 0 0 0 0.206463 0 0 0 0.04 0\"/>\n<feBlend mode=\"normal\" in2=\"effect1_dropShadow_1_117\" result=\"effect2_dropShadow_1_117\"/>\n<feBlend mode=\"normal\" in=\"SourceGraphic\" in2=\"effect2_dropShadow_1_117\" result=\"shape\"/>\n</filter>\n<filter id=\"filter2_d_1_117\" x=\"105\" y=\"106\" width=\"62\" height=\"62\" filterUnits=\"userSpaceOnUse\" color-interpolation-filters=\"sRGB\">\n<feFlood flood-opacity=\"0\" result=\"BackgroundImageFix\"/>\n<feColorMatrix in=\"SourceAlpha\" type=\"matrix\" values=\"0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0\" result=\"hardAlpha\"/>\n<feOffset dy=\"1\"/>\n<feGaussianBlur stdDeviation=\"1.5\"/>\n<feComposite in2=\"hardAlpha\" operator=\"out\"/>\n<feColorMatrix type=\"matrix\" values=\"0 0 0 0 0.1056 0 0 0 0 0.11904 0 0 0 0 0.1344 0 0 0 0.16 0\"/>\n<feBlend mode=\"normal\" in2=\"BackgroundImageFix\" result=\"effect1_dropShadow_1_117\"/>\n<feBlend mode=\"normal\" in=\"SourceGraphic\" in2=\"effect1_dropShadow_1_117\" result=\"shape\"/>\n</filter>\n<clipPath id=\"clip0_1_117\">\n<rect width=\"164\" height=\"164\" rx=\"82\" fill=\"white\"/>\n</clipPath>\n<clipPath id=\"clip1_1_117\">\n<rect x=\"32\" y=\"36\" width=\"256\" height=\"140\" rx=\"6\" fill=\"white\"/>\n</clipPath>\n</defs>\n</svg>\n","<svg width=\"164\" height=\"164\" viewBox=\"0 0 164 164\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\">\n<g filter=\"url(#filter0_i_4124_102997)\">\n<g clip-path=\"url(#clip0_4124_102997)\">\n<rect width=\"164\" height=\"164\" rx=\"82\" fill=\"#F9FAFB\"/>\n<g filter=\"url(#filter1_dd_4124_102997)\">\n<g clip-path=\"url(#clip1_4124_102997)\">\n<rect x=\"16\" y=\"48\" width=\"132\" height=\"124\" rx=\"4\" fill=\"white\"/>\n<rect width=\"132\" height=\"12\" transform=\"translate(16 48)\" fill=\"#454D5F\"/>\n<circle opacity=\"0.24\" cx=\"23\" cy=\"54\" r=\"3\" fill=\"white\"/>\n<rect opacity=\"0.24\" x=\"30\" y=\"53\" width=\"10\" height=\"2\" rx=\"1\" fill=\"white\"/>\n<g clip-path=\"url(#clip2_4124_102997)\">\n<rect width=\"132\" height=\"132\" transform=\"translate(16 60)\" fill=\"white\"/>\n<rect opacity=\"0.16\" x=\"40\" y=\"160\" width=\"16\" height=\"2\" rx=\"1\" fill=\"#454D5F\"/>\n<rect opacity=\"0.24\" x=\"120\" y=\"158\" width=\"6\" height=\"6\" rx=\"1.5\" fill=\"#454D5F\"/>\n<rect opacity=\"0.24\" x=\"24\" y=\"157\" width=\"8\" height=\"8\" rx=\"4\" fill=\"#454D5F\"/>\n</g>\n<path d=\"M68.8367 113.863V117.613H48.3289L48.1727 114.781L60.4383 95.5625H64.2078L60.1258 102.555L53.075 113.863H68.8367ZM65.282 95.5625V124H60.575V95.5625H65.282ZM91.3164 107.398V112.047C91.3164 114.273 91.0951 116.174 90.6523 117.75C90.2227 119.312 89.5977 120.582 88.7773 121.559C87.957 122.535 86.974 123.251 85.8281 123.707C84.6953 124.163 83.4258 124.391 82.0195 124.391C80.8997 124.391 79.8581 124.247 78.8945 123.961C77.944 123.674 77.0846 123.225 76.3164 122.613C75.5482 122.001 74.8906 121.214 74.3438 120.25C73.8099 119.273 73.3932 118.108 73.0938 116.754C72.8073 115.4 72.6641 113.831 72.6641 112.047V107.398C72.6641 105.159 72.8854 103.271 73.3281 101.734C73.7708 100.185 74.4023 98.9284 75.2227 97.9648C76.043 96.9883 77.0195 96.2786 78.1523 95.8359C79.2982 95.3932 80.5742 95.1719 81.9805 95.1719C83.1133 95.1719 84.1549 95.3151 85.1055 95.6016C86.069 95.875 86.9284 96.3112 87.6836 96.9102C88.4518 97.5091 89.1029 98.2904 89.6367 99.2539C90.1836 100.204 90.6003 101.357 90.8867 102.711C91.1732 104.052 91.3164 105.615 91.3164 107.398ZM86.6094 112.711V106.695C86.6094 105.562 86.5443 104.566 86.4141 103.707C86.2839 102.835 86.0885 102.099 85.8281 101.5C85.5807 100.888 85.2682 100.393 84.8906 100.016C84.513 99.625 84.0833 99.3451 83.6016 99.1758C83.1198 98.9935 82.5794 98.9023 81.9805 98.9023C81.2513 98.9023 80.6003 99.0456 80.0273 99.332C79.4544 99.6055 78.9727 100.048 78.582 100.66C78.1914 101.272 77.8919 102.079 77.6836 103.082C77.4883 104.072 77.3906 105.276 77.3906 106.695V112.711C77.3906 113.857 77.4557 114.866 77.5859 115.738C77.7161 116.611 77.9115 117.359 78.1719 117.984C78.4323 118.596 78.7448 119.104 79.1094 119.508C79.487 119.898 79.9167 120.185 80.3984 120.367C80.8932 120.549 81.4336 120.641 82.0195 120.641C82.7617 120.641 83.4193 120.497 83.9922 120.211C84.5651 119.924 85.0469 119.469 85.4375 118.844C85.8281 118.206 86.1211 117.379 86.3164 116.363C86.5117 115.348 86.6094 114.13 86.6094 112.711ZM115.905 113.863V117.613H95.3977L95.2414 114.781L107.507 95.5625H111.277L107.195 102.555L100.144 113.863H115.905ZM112.351 95.5625V124H107.644V95.5625H112.351Z\" fill=\"#C6CAD2\"/>\n</g>\n</g>\n</g>\n</g>\n<defs>\n<filter id=\"filter0_i_4124_102997\" x=\"0\" y=\"-1\" width=\"164\" height=\"165\" filterUnits=\"userSpaceOnUse\" color-interpolation-filters=\"sRGB\">\n<feFlood flood-opacity=\"0\" result=\"BackgroundImageFix\"/>\n<feBlend mode=\"normal\" in=\"SourceGraphic\" in2=\"BackgroundImageFix\" result=\"shape\"/>\n<feColorMatrix in=\"SourceAlpha\" type=\"matrix\" values=\"0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0\" result=\"hardAlpha\"/>\n<feOffset dy=\"-1\"/>\n<feGaussianBlur stdDeviation=\"1.5\"/>\n<feComposite in2=\"hardAlpha\" operator=\"arithmetic\" k2=\"-1\" k3=\"1\"/>\n<feColorMatrix type=\"matrix\" values=\"0 0 0 0 0.1056 0 0 0 0 0.11904 0 0 0 0 0.1344 0 0 0 0.2 0\"/>\n<feBlend mode=\"normal\" in2=\"shape\" result=\"effect1_innerShadow_4124_102997\"/>\n</filter>\n<filter id=\"filter1_dd_4124_102997\" x=\"13\" y=\"46\" width=\"138\" height=\"130\" filterUnits=\"userSpaceOnUse\" color-interpolation-filters=\"sRGB\">\n<feFlood flood-opacity=\"0\" result=\"BackgroundImageFix\"/>\n<feColorMatrix in=\"SourceAlpha\" type=\"matrix\" values=\"0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0\" result=\"hardAlpha\"/>\n<feOffset/>\n<feGaussianBlur stdDeviation=\"0.5\"/>\n<feComposite in2=\"hardAlpha\" operator=\"out\"/>\n<feColorMatrix type=\"matrix\" values=\"0 0 0 0 0.0335371 0 0 0 0 0.206463 0 0 0 0 0.183406 0 0 0 0.12 0\"/>\n<feBlend mode=\"normal\" in2=\"BackgroundImageFix\" result=\"effect1_dropShadow_4124_102997\"/>\n<feColorMatrix in=\"SourceAlpha\" type=\"matrix\" values=\"0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0\" result=\"hardAlpha\"/>\n<feOffset dy=\"1\"/>\n<feGaussianBlur stdDeviation=\"1.5\"/>\n<feComposite in2=\"hardAlpha\" operator=\"out\"/>\n<feColorMatrix type=\"matrix\" values=\"0 0 0 0 0.0335371 0 0 0 0 0.206463 0 0 0 0 0.183406 0 0 0 0.04 0\"/>\n<feBlend mode=\"normal\" in2=\"effect1_dropShadow_4124_102997\" result=\"effect2_dropShadow_4124_102997\"/>\n<feBlend mode=\"normal\" in=\"SourceGraphic\" in2=\"effect2_dropShadow_4124_102997\" result=\"shape\"/>\n</filter>\n<clipPath id=\"clip0_4124_102997\">\n<rect width=\"164\" height=\"164\" rx=\"82\" fill=\"white\"/>\n</clipPath>\n<clipPath id=\"clip1_4124_102997\">\n<rect x=\"16\" y=\"48\" width=\"132\" height=\"124\" rx=\"4\" fill=\"white\"/>\n</clipPath>\n<clipPath id=\"clip2_4124_102997\">\n<rect width=\"132\" height=\"132\" fill=\"white\" transform=\"translate(16 60)\"/>\n</clipPath>\n</defs>\n</svg>\n","<svg width=\"164\" height=\"164\" viewBox=\"0 0 164 164\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\">\n<g filter=\"url(#filter0_i_4124_103042)\">\n<g clip-path=\"url(#clip0_4124_103042)\">\n<rect width=\"164\" height=\"164\" rx=\"82\" fill=\"#F9FAFB\"/>\n<g filter=\"url(#filter1_dd_4124_103042)\">\n<g clip-path=\"url(#clip1_4124_103042)\">\n<rect x=\"16\" y=\"48\" width=\"132\" height=\"124\" rx=\"4\" fill=\"white\"/>\n<rect width=\"132\" height=\"12\" transform=\"translate(16 48)\" fill=\"#454D5F\"/>\n<circle opacity=\"0.24\" cx=\"23\" cy=\"54\" r=\"3\" fill=\"white\"/>\n<rect opacity=\"0.24\" x=\"30\" y=\"53\" width=\"10\" height=\"2\" rx=\"1\" fill=\"white\"/>\n<g clip-path=\"url(#clip2_4124_103042)\">\n<rect width=\"132\" height=\"132\" transform=\"translate(16 60)\" fill=\"white\"/>\n<rect opacity=\"0.16\" x=\"40\" y=\"160\" width=\"16\" height=\"2\" rx=\"1\" fill=\"#454D5F\"/>\n<rect opacity=\"0.24\" x=\"120\" y=\"158\" width=\"6\" height=\"6\" rx=\"1.5\" fill=\"#454D5F\"/>\n<rect opacity=\"0.24\" x=\"24\" y=\"157\" width=\"8\" height=\"8\" rx=\"4\" fill=\"#454D5F\"/>\n<path d=\"M54.1883 110.777L50.4383 109.859L51.9813 95.5625H67.3133V99.5469H55.8875L55.1063 106.52C55.549 106.259 56.1609 106.005 56.9422 105.758C57.7234 105.497 58.6154 105.367 59.618 105.367C60.9591 105.367 62.157 105.589 63.2117 106.031C64.2794 106.461 65.1844 107.092 65.9266 107.926C66.6688 108.746 67.2352 109.749 67.6258 110.934C68.0164 112.105 68.2117 113.427 68.2117 114.898C68.2117 116.214 68.0164 117.444 67.6258 118.59C67.2482 119.736 66.6753 120.745 65.907 121.617C65.1388 122.49 64.1688 123.173 62.9969 123.668C61.838 124.15 60.4643 124.391 58.8758 124.391C57.6909 124.391 56.5516 124.221 55.4578 123.883C54.3771 123.531 53.407 123.017 52.5477 122.34C51.6883 121.65 50.9982 120.803 50.4773 119.801C49.9565 118.785 49.657 117.62 49.5789 116.305H54.1883C54.3055 117.229 54.5594 118.017 54.95 118.668C55.3536 119.306 55.8875 119.794 56.5516 120.133C57.2156 120.471 57.9839 120.641 58.8563 120.641C59.6505 120.641 60.3341 120.504 60.907 120.23C61.4799 119.944 61.9552 119.54 62.3328 119.02C62.7234 118.486 63.0099 117.861 63.1922 117.145C63.3875 116.428 63.4852 115.634 63.4852 114.762C63.4852 113.928 63.3745 113.167 63.1531 112.477C62.9448 111.786 62.6258 111.188 62.1961 110.68C61.7794 110.172 61.2521 109.781 60.6141 109.508C59.976 109.221 59.2404 109.078 58.407 109.078C57.2872 109.078 56.4279 109.241 55.8289 109.566C55.243 109.892 54.6961 110.296 54.1883 110.777ZM91.3164 107.398V112.047C91.3164 114.273 91.0951 116.174 90.6523 117.75C90.2227 119.312 89.5977 120.582 88.7773 121.559C87.957 122.535 86.974 123.251 85.8281 123.707C84.6953 124.163 83.4258 124.391 82.0195 124.391C80.8997 124.391 79.8581 124.247 78.8945 123.961C77.944 123.674 77.0846 123.225 76.3164 122.613C75.5482 122.001 74.8906 121.214 74.3438 120.25C73.8099 119.273 73.3932 118.108 73.0938 116.754C72.8073 115.4 72.6641 113.831 72.6641 112.047V107.398C72.6641 105.159 72.8854 103.271 73.3281 101.734C73.7708 100.185 74.4023 98.9284 75.2227 97.9648C76.043 96.9883 77.0195 96.2786 78.1523 95.8359C79.2982 95.3932 80.5742 95.1719 81.9805 95.1719C83.1133 95.1719 84.1549 95.3151 85.1055 95.6016C86.069 95.875 86.9284 96.3112 87.6836 96.9102C88.4518 97.5091 89.1029 98.2904 89.6367 99.2539C90.1836 100.204 90.6003 101.357 90.8867 102.711C91.1732 104.052 91.3164 105.615 91.3164 107.398ZM86.6094 112.711V106.695C86.6094 105.562 86.5443 104.566 86.4141 103.707C86.2839 102.835 86.0885 102.099 85.8281 101.5C85.5807 100.888 85.2682 100.393 84.8906 100.016C84.513 99.625 84.0833 99.3451 83.6016 99.1758C83.1198 98.9935 82.5794 98.9023 81.9805 98.9023C81.2513 98.9023 80.6003 99.0456 80.0273 99.332C79.4544 99.6055 78.9727 100.048 78.582 100.66C78.1914 101.272 77.8919 102.079 77.6836 103.082C77.4883 104.072 77.3906 105.276 77.3906 106.695V112.711C77.3906 113.857 77.4557 114.866 77.5859 115.738C77.7161 116.611 77.9115 117.359 78.1719 117.984C78.4323 118.596 78.7448 119.104 79.1094 119.508C79.487 119.898 79.9167 120.185 80.3984 120.367C80.8932 120.549 81.4336 120.641 82.0195 120.641C82.7617 120.641 83.4193 120.497 83.9922 120.211C84.5651 119.924 85.0469 119.469 85.4375 118.844C85.8281 118.206 86.1211 117.379 86.3164 116.363C86.5117 115.348 86.6094 114.13 86.6094 112.711ZM114.851 107.398V112.047C114.851 114.273 114.629 116.174 114.187 117.75C113.757 119.312 113.132 120.582 112.312 121.559C111.491 122.535 110.508 123.251 109.362 123.707C108.23 124.163 106.96 124.391 105.554 124.391C104.434 124.391 103.392 124.247 102.429 123.961C101.478 123.674 100.619 123.225 99.8508 122.613C99.0826 122.001 98.425 121.214 97.8781 120.25C97.3443 119.273 96.9276 118.108 96.6281 116.754C96.3417 115.4 96.1984 113.831 96.1984 112.047V107.398C96.1984 105.159 96.4198 103.271 96.8625 101.734C97.3052 100.185 97.9367 98.9284 98.757 97.9648C99.5773 96.9883 100.554 96.2786 101.687 95.8359C102.833 95.3932 104.109 95.1719 105.515 95.1719C106.648 95.1719 107.689 95.3151 108.64 95.6016C109.603 95.875 110.463 96.3112 111.218 96.9102C111.986 97.5091 112.637 98.2904 113.171 99.2539C113.718 100.204 114.135 101.357 114.421 102.711C114.708 104.052 114.851 105.615 114.851 107.398ZM110.144 112.711V106.695C110.144 105.562 110.079 104.566 109.948 103.707C109.818 102.835 109.623 102.099 109.362 101.5C109.115 100.888 108.803 100.393 108.425 100.016C108.047 99.625 107.618 99.3451 107.136 99.1758C106.654 98.9935 106.114 98.9023 105.515 98.9023C104.786 98.9023 104.135 99.0456 103.562 99.332C102.989 99.6055 102.507 100.048 102.116 100.66C101.726 101.272 101.426 102.079 101.218 103.082C101.023 104.072 100.925 105.276 100.925 106.695V112.711C100.925 113.857 100.99 114.866 101.12 115.738C101.251 116.611 101.446 117.359 101.706 117.984C101.967 118.596 102.279 119.104 102.644 119.508C103.021 119.898 103.451 120.185 103.933 120.367C104.428 120.549 104.968 120.641 105.554 120.641C106.296 120.641 106.954 120.497 107.527 120.211C108.099 119.924 108.581 119.469 108.972 118.844C109.362 118.206 109.655 117.379 109.851 116.363C110.046 115.348 110.144 114.13 110.144 112.711Z\" fill=\"#C6CAD2\"/>\n</g>\n</g>\n</g>\n</g>\n</g>\n<defs>\n<filter id=\"filter0_i_4124_103042\" x=\"0\" y=\"-1\" width=\"164\" height=\"165\" filterUnits=\"userSpaceOnUse\" color-interpolation-filters=\"sRGB\">\n<feFlood flood-opacity=\"0\" result=\"BackgroundImageFix\"/>\n<feBlend mode=\"normal\" in=\"SourceGraphic\" in2=\"BackgroundImageFix\" result=\"shape\"/>\n<feColorMatrix in=\"SourceAlpha\" type=\"matrix\" values=\"0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0\" result=\"hardAlpha\"/>\n<feOffset dy=\"-1\"/>\n<feGaussianBlur stdDeviation=\"1.5\"/>\n<feComposite in2=\"hardAlpha\" operator=\"arithmetic\" k2=\"-1\" k3=\"1\"/>\n<feColorMatrix type=\"matrix\" values=\"0 0 0 0 0.1056 0 0 0 0 0.11904 0 0 0 0 0.1344 0 0 0 0.2 0\"/>\n<feBlend mode=\"normal\" in2=\"shape\" result=\"effect1_innerShadow_4124_103042\"/>\n</filter>\n<filter id=\"filter1_dd_4124_103042\" x=\"13\" y=\"46\" width=\"138\" height=\"130\" filterUnits=\"userSpaceOnUse\" color-interpolation-filters=\"sRGB\">\n<feFlood flood-opacity=\"0\" result=\"BackgroundImageFix\"/>\n<feColorMatrix in=\"SourceAlpha\" type=\"matrix\" values=\"0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0\" result=\"hardAlpha\"/>\n<feOffset/>\n<feGaussianBlur stdDeviation=\"0.5\"/>\n<feComposite in2=\"hardAlpha\" operator=\"out\"/>\n<feColorMatrix type=\"matrix\" values=\"0 0 0 0 0.0335371 0 0 0 0 0.206463 0 0 0 0 0.183406 0 0 0 0.12 0\"/>\n<feBlend mode=\"normal\" in2=\"BackgroundImageFix\" result=\"effect1_dropShadow_4124_103042\"/>\n<feColorMatrix in=\"SourceAlpha\" type=\"matrix\" values=\"0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0\" result=\"hardAlpha\"/>\n<feOffset dy=\"1\"/>\n<feGaussianBlur stdDeviation=\"1.5\"/>\n<feComposite in2=\"hardAlpha\" operator=\"out\"/>\n<feColorMatrix type=\"matrix\" values=\"0 0 0 0 0.0335371 0 0 0 0 0.206463 0 0 0 0 0.183406 0 0 0 0.04 0\"/>\n<feBlend mode=\"normal\" in2=\"effect1_dropShadow_4124_103042\" result=\"effect2_dropShadow_4124_103042\"/>\n<feBlend mode=\"normal\" in=\"SourceGraphic\" in2=\"effect2_dropShadow_4124_103042\" result=\"shape\"/>\n</filter>\n<clipPath id=\"clip0_4124_103042\">\n<rect width=\"164\" height=\"164\" rx=\"82\" fill=\"white\"/>\n</clipPath>\n<clipPath id=\"clip1_4124_103042\">\n<rect x=\"16\" y=\"48\" width=\"132\" height=\"124\" rx=\"4\" fill=\"white\"/>\n</clipPath>\n<clipPath id=\"clip2_4124_103042\">\n<rect width=\"132\" height=\"132\" fill=\"white\" transform=\"translate(16 60)\"/>\n</clipPath>\n</defs>\n</svg>\n","<svg width=\"164\" height=\"164\" viewBox=\"0 0 164 164\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\">\n<g filter=\"url(#filter0_i_7107_90986)\">\n<g clip-path=\"url(#clip0_7107_90986)\">\n<rect width=\"164\" height=\"164\" rx=\"82\" fill=\"#F9FAFB\"/>\n<g filter=\"url(#filter1_dd_7107_90986)\">\n<rect x=\"38.588\" y=\"31.1113\" width=\"256\" height=\"140\" rx=\"6\" transform=\"rotate(5 38.588 31.1113)\" fill=\"white\" shape-rendering=\"crispEdges\"/>\n<rect x=\"49.6952\" y=\"53.4668\" width=\"104\" height=\"36\" rx=\"4\" transform=\"rotate(8 49.6952 53.4668)\" fill=\"#F3F4F6\"/>\n<rect width=\"230\" height=\"12\" transform=\"translate(-1.77661 60.6738) rotate(-10)\" fill=\"#454D5F\"/>\n<circle opacity=\"0.24\" cx=\"6.15896\" cy=\"65.3671\" r=\"3\" transform=\"rotate(-10 6.15896 65.3671)\" fill=\"white\"/>\n<rect opacity=\"0.24\" x=\"12.8789\" y=\"63.166\" width=\"10\" height=\"2\" rx=\"1\" transform=\"rotate(-10 12.8789 63.166)\" fill=\"white\"/>\n<rect x=\"43.9305\" y=\"100.689\" width=\"48\" height=\"36\" rx=\"4\" transform=\"rotate(3 43.9305 100.689)\" fill=\"#F3F4F6\"/>\n<rect x=\"41.8835\" y=\"146.205\" width=\"48\" height=\"36\" rx=\"4\" transform=\"rotate(9 41.8835 146.205)\" fill=\"#F3F4F6\"/>\n<rect x=\"101.884\" y=\"106.895\" width=\"48\" height=\"36\" rx=\"4\" transform=\"rotate(10 101.884 106.895)\" fill=\"#F3F4F6\"/>\n<rect x=\"96.3936\" y=\"150.604\" width=\"48\" height=\"36\" rx=\"4\" transform=\"rotate(5 96.3936 150.604)\" fill=\"#F3F4F6\"/>\n</g>\n</g>\n</g>\n<defs>\n<filter id=\"filter0_i_7107_90986\" x=\"0\" y=\"-1\" width=\"164\" height=\"165\" filterUnits=\"userSpaceOnUse\" color-interpolation-filters=\"sRGB\">\n<feFlood flood-opacity=\"0\" result=\"BackgroundImageFix\"/>\n<feBlend mode=\"normal\" in=\"SourceGraphic\" in2=\"BackgroundImageFix\" result=\"shape\"/>\n<feColorMatrix in=\"SourceAlpha\" type=\"matrix\" values=\"0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0\" result=\"hardAlpha\"/>\n<feOffset dy=\"-1\"/>\n<feGaussianBlur stdDeviation=\"1.5\"/>\n<feComposite in2=\"hardAlpha\" operator=\"arithmetic\" k2=\"-1\" k3=\"1\"/>\n<feColorMatrix type=\"matrix\" values=\"0 0 0 0 0.1056 0 0 0 0 0.11904 0 0 0 0 0.1344 0 0 0 0.2 0\"/>\n<feBlend mode=\"normal\" in2=\"shape\" result=\"effect1_innerShadow_7107_90986\"/>\n</filter>\n<filter id=\"filter1_dd_7107_90986\" x=\"-4.77661\" y=\"18.7344\" width=\"301.391\" height=\"178.156\" filterUnits=\"userSpaceOnUse\" color-interpolation-filters=\"sRGB\">\n<feFlood flood-opacity=\"0\" result=\"BackgroundImageFix\"/>\n<feColorMatrix in=\"SourceAlpha\" type=\"matrix\" values=\"0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0\" result=\"hardAlpha\"/>\n<feOffset/>\n<feGaussianBlur stdDeviation=\"1\"/>\n<feComposite in2=\"hardAlpha\" operator=\"out\"/>\n<feColorMatrix type=\"matrix\" values=\"0 0 0 0 0.0775545 0 0 0 0 0.0335371 0 0 0 0 0.206463 0 0 0 0.12 0\"/>\n<feBlend mode=\"normal\" in2=\"BackgroundImageFix\" result=\"effect1_dropShadow_7107_90986\"/>\n<feColorMatrix in=\"SourceAlpha\" type=\"matrix\" values=\"0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0\" result=\"hardAlpha\"/>\n<feOffset dy=\"1\"/>\n<feGaussianBlur stdDeviation=\"1.5\"/>\n<feComposite in2=\"hardAlpha\" operator=\"out\"/>\n<feColorMatrix type=\"matrix\" values=\"0 0 0 0 0.0775545 0 0 0 0 0.0335371 0 0 0 0 0.206463 0 0 0 0.04 0\"/>\n<feBlend mode=\"normal\" in2=\"effect1_dropShadow_7107_90986\" result=\"effect2_dropShadow_7107_90986\"/>\n<feBlend mode=\"normal\" in=\"SourceGraphic\" in2=\"effect2_dropShadow_7107_90986\" result=\"shape\"/>\n</filter>\n<clipPath id=\"clip0_7107_90986\">\n<rect width=\"164\" height=\"164\" rx=\"82\" fill=\"white\"/>\n</clipPath>\n</defs>\n</svg>\n","<svg width=\"164\" height=\"164\" viewBox=\"0 0 164 164\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\">\n<g filter=\"url(#filter0_i_7083_91308)\">\n<g clip-path=\"url(#clip0_7083_91308)\">\n<rect width=\"164\" height=\"164\" rx=\"82\" fill=\"#F9FAFB\"/>\n<g filter=\"url(#filter1_dd_7083_91308)\">\n<rect x=\"16\" y=\"48\" width=\"132\" height=\"128\" rx=\"4\" fill=\"white\"/>\n<circle cx=\"82\" cy=\"72\" r=\"12\" fill=\"#E8EAED\"/>\n<rect x=\"67\" y=\"92\" width=\"30\" height=\"6\" rx=\"3\" fill=\"#E8EAED\"/>\n<rect x=\"31\" y=\"114.002\" width=\"102\" height=\"16\" rx=\"4\" fill=\"#E8EAED\"/>\n<rect x=\"31\" y=\"142.002\" width=\"102\" height=\"16\" rx=\"4\" fill=\"#E8EAED\"/>\n</g>\n</g>\n</g>\n<defs>\n<filter id=\"filter0_i_7083_91308\" x=\"0\" y=\"-1\" width=\"164\" height=\"165\" filterUnits=\"userSpaceOnUse\" color-interpolation-filters=\"sRGB\">\n<feFlood flood-opacity=\"0\" result=\"BackgroundImageFix\"/>\n<feBlend mode=\"normal\" in=\"SourceGraphic\" in2=\"BackgroundImageFix\" result=\"shape\"/>\n<feColorMatrix in=\"SourceAlpha\" type=\"matrix\" values=\"0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0\" result=\"hardAlpha\"/>\n<feOffset dy=\"-1\"/>\n<feGaussianBlur stdDeviation=\"1.5\"/>\n<feComposite in2=\"hardAlpha\" operator=\"arithmetic\" k2=\"-1\" k3=\"1\"/>\n<feColorMatrix type=\"matrix\" values=\"0 0 0 0 0.1056 0 0 0 0 0.11904 0 0 0 0 0.1344 0 0 0 0.2 0\"/>\n<feBlend mode=\"normal\" in2=\"shape\" result=\"effect1_innerShadow_7083_91308\"/>\n</filter>\n<filter id=\"filter1_dd_7083_91308\" x=\"13\" y=\"46\" width=\"138\" height=\"134\" filterUnits=\"userSpaceOnUse\" color-interpolation-filters=\"sRGB\">\n<feFlood flood-opacity=\"0\" result=\"BackgroundImageFix\"/>\n<feColorMatrix in=\"SourceAlpha\" type=\"matrix\" values=\"0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0\" result=\"hardAlpha\"/>\n<feOffset/>\n<feGaussianBlur stdDeviation=\"0.5\"/>\n<feComposite in2=\"hardAlpha\" operator=\"out\"/>\n<feColorMatrix type=\"matrix\" values=\"0 0 0 0 0.0335371 0 0 0 0 0.206463 0 0 0 0 0.183406 0 0 0 0.12 0\"/>\n<feBlend mode=\"normal\" in2=\"BackgroundImageFix\" result=\"effect1_dropShadow_7083_91308\"/>\n<feColorMatrix in=\"SourceAlpha\" type=\"matrix\" values=\"0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0\" result=\"hardAlpha\"/>\n<feOffset dy=\"1\"/>\n<feGaussianBlur stdDeviation=\"1.5\"/>\n<feComposite in2=\"hardAlpha\" operator=\"out\"/>\n<feColorMatrix type=\"matrix\" values=\"0 0 0 0 0.0335371 0 0 0 0 0.206463 0 0 0 0 0.183406 0 0 0 0.04 0\"/>\n<feBlend mode=\"normal\" in2=\"effect1_dropShadow_7083_91308\" result=\"effect2_dropShadow_7083_91308\"/>\n<feBlend mode=\"normal\" in=\"SourceGraphic\" in2=\"effect2_dropShadow_7083_91308\" result=\"shape\"/>\n</filter>\n<clipPath id=\"clip0_7083_91308\">\n<rect width=\"164\" height=\"164\" rx=\"82\" fill=\"white\"/>\n</clipPath>\n</defs>\n</svg>\n","import React from \"react\";\nimport styled from \"styled-components\";\nimport ForbiddenErrorImage from \"../assets/images/errors/403-image.svg\";\nimport AppNotFoundImage from \"../assets/images/errors/404-image.svg\";\nimport ServerError500Image from \"../assets/images/errors/500-image.svg\";\nimport GeneralErrorImage from \"../assets/images/errors/general-error.svg\";\nimport LoginErrorImage from \"../assets/images/errors/login-error.svg\";\nimport { colors } from \"../styling/colors.js\";\nimport { API_STATUS_CODES } from \"./constants.js\";\n\nconst HOME_URL = \"/home\";\n\nconst VerticalWrapper = styled.div`\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n height: 100%;\n`;\n\ninterface Props {\n title: string;\n errorMessage?: string | React.ReactNode;\n buttonText?: string;\n handleButtonClick?: () => void;\n errorCode?: API_STATUS_CODES | \"LOGIN_FAILURE\";\n buttonPath?: string;\n image?: string; // when not set, the image will be based on the errorCode\n secondaryButtonText?: string;\n secondaryButtonAction?: () => void;\n hideActions?: boolean;\n mainButtonType?: \"primary\" | \"ghost\";\n // showActionsOnEmbedRoute?: boolean; // by default, actions are hidden on embed pages\n}\n\n// Most of the errors have this styling anyway\nconst ErrorWrapper = styled.div`\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n height: calc(100vh);\n text-align: center;\n .bold-text {\n font-weight: 500;\n font-size: 24px;\n }\n .page-unavailable-img {\n width: 35%;\n }\n .button-position {\n margin: auto;\n }\n`;\n\nconst TextWrapper = styled.div`\n margin-top: 30px;\n margin-bottom: 30px;\n max-width: 500px;\n`;\n\nconst Title = styled.h3`\n font-size: 1.25rem;\n font-weight: 500;\n margin-bottom: 0.5rem;\n`;\n\nconst ErrorMessage = styled.p`\n color: ${colors.GREY_500};\n`;\n\nconst Button = styled.button`\n border: 1px solid ${colors.GREY_100};\n color: ${colors.GREY_600};\n border-radius: 6px;\n padding: 2px 6px;\n font-size: 1rem;\n font-weight: 400;\n cursor: pointer;\n\n &:hover {\n background-color: ${colors.GREY_100};\n }\n`;\n\nconst ErrorComponent = ({\n title,\n errorMessage,\n buttonText,\n handleButtonClick,\n errorCode,\n buttonPath,\n image: overrideImage,\n secondaryButtonAction,\n secondaryButtonText,\n hideActions,\n}: Props) => {\n let ImageComponent = overrideImage ?? GeneralErrorImage;\n if (!overrideImage) {\n switch (errorCode) {\n case API_STATUS_CODES.RESOURCE_NOT_FOUND:\n ImageComponent = AppNotFoundImage;\n break;\n case API_STATUS_CODES.SERVER_ERROR:\n ImageComponent = ServerError500Image;\n break;\n case API_STATUS_CODES.RESOURCE_FORBIDDEN:\n ImageComponent = ForbiddenErrorImage;\n break;\n case API_STATUS_CODES.TIMEOUT:\n ImageComponent = GeneralErrorImage;\n break;\n case \"LOGIN_FAILURE\":\n ImageComponent = LoginErrorImage;\n break;\n default:\n ImageComponent = GeneralErrorImage; //we should have covered all the cases and Koala should not show, keeping it here since we do not have a default one\n }\n }\n const showActions = !hideActions;\n\n return (\n <ErrorWrapper data-test=\"app-error-container\" className=\"error-wrapper\">\n <VerticalWrapper>\n <ImageComponent />\n <TextWrapper>\n <Title>{title}</Title>\n {errorMessage && (\n <ErrorMessage data-test=\"error-page-subtext\">\n {errorMessage}\n </ErrorMessage>\n )}\n </TextWrapper>\n {showActions && (\n <div style={{ display: \"flex\", alignItems: \"center\", gap: \"12px\" }}>\n {secondaryButtonText && secondaryButtonAction && (\n <Button type=\"button\" onClick={secondaryButtonAction}>\n {secondaryButtonText}\n </Button>\n )}\n <Button\n type={\"button\"}\n onClick={() =>\n handleButtonClick\n ? handleButtonClick()\n : (window.location.pathname = buttonPath ?? HOME_URL)\n }\n data-test=\"error-component-button\"\n >\n {buttonText ? buttonText : \"Return Home\"}\n </Button>\n </div>\n )}\n </VerticalWrapper>\n </ErrorWrapper>\n );\n};\n\nexport default ErrorComponent;\n","import React from \"react\";\nimport styled from \"styled-components\";\nimport { API_STATUS_CODES } from \"./constants.js\";\nimport ErrorComponent from \"./error-component.jsx\";\n\nconst Wrapper = styled.div`\n text-align: center;\n .bold-text {\n font-weight: 500;\n font-size: 24px;\n }\n .page-unavailable-img {\n width: 35%;\n }\n .button-position {\n margin: auto;\n }\n height: 100%;\n`;\n\nexport const PageNotFound = ({\n title = \"Content not found\",\n errorMessage = \"We couldn’t find the page you were looking for. Make sure that you have the right URL. \",\n buttonPath,\n buttonText,\n onButtonClick,\n hideActions,\n}: {\n title?: string;\n errorMessage?: string | React.ReactElement;\n buttonPath?: string;\n buttonText?: string;\n onButtonClick?: () => void;\n hideActions?: boolean;\n}) => {\n return (\n <Wrapper>\n <ErrorComponent\n errorCode={API_STATUS_CODES.RESOURCE_NOT_FOUND}\n title={title}\n errorMessage={errorMessage}\n hideActions={hideActions}\n buttonPath={buttonPath}\n buttonText={buttonText}\n mainButtonType={\"ghost\"}\n handleButtonClick={onButtonClick}\n />\n </Wrapper>\n );\n};\n","import { useEffect } from \"react\";\nimport { useRouteError } from \"react-router\";\nimport { editorBridge } from \"../../../edit-mode/superblocks-editor-bridge.js\";\nimport { isEditMode } from \"../is-edit-mode.js\";\nimport {\n ErrorIconContainer,\n ErrorTitle,\n ErrorMessage,\n ErrorStack,\n ErrorDetails,\n StyledClarkIcon,\n ErrorContainer,\n ErrorContent,\n ErrorSummary,\n SecondaryButton,\n ActionsContainer,\n} from \"./common.js\";\nimport { FixWithClarkButton } from \"./fix-with-clark-button.jsx\";\n\nexport function RouteLoadError() {\n const error = useRouteError() as Error;\n\n // we do this dynamically because this component will probably be loaded\n // before the app has even bootstrapped, because we have an error during route loading\n // (i.e. syntax error, missing import, etc.)\n useEffect(() => {\n const link = document.createElement(\"link\");\n link.href =\n \"https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap\";\n link.rel = \"stylesheet\";\n document.head.appendChild(link);\n // send a message to the ui to remove the loading state\n editorBridge.sendReady();\n if (isEditMode()) {\n editorBridge.sendLoadError(String(error));\n }\n\n return () => {\n document.head.removeChild(link);\n };\n }, [error]);\n\n console.error(\"Route load error\", error);\n return (\n <ErrorContainer>\n <ErrorContent>\n <ErrorIconContainer>\n <StyledClarkIcon />\n </ErrorIconContainer>\n\n <ErrorTitle>Something went wrong</ErrorTitle>\n <ErrorMessage>{error?.message || \"Unknown error\"}</ErrorMessage>\n\n <ActionsContainer>\n {isEditMode() && <FixWithClarkButton error={error} />}\n <SecondaryButton\n onClick={() => {\n window.location.reload();\n }}\n >\n Refresh page\n </SecondaryButton>\n </ActionsContainer>\n\n {error && (\n <ErrorDetails>\n <ErrorSummary>Full details</ErrorSummary>\n <ErrorStack>{error.stack}</ErrorStack>\n </ErrorDetails>\n )}\n </ErrorContent>\n </ErrorContainer>\n );\n}\n","import \"../edit-mode/edit-style.css\";\n\n// CRITICAL: Early console patching before any other JS imports\nimport LibraryEarlyConsoleBuffer from \"./tracing/early-console-buffer.js\";\nLibraryEarlyConsoleBuffer.getInstance().patchEarly();\n\n// Register all standard HTML elements with default properties panels\nimport { registerHtmlElements } from \"./user-facing/components/html/register-html-elements.js\";\nregisterHtmlElements();\n\nimport type { CreateChild } from \"@superblocksteam/library-shared/types\";\nexport { type CreateChild };\n\n// Superblocks Global Context\nexport { default as SuperblocksProvider } from \"./user-facing/sb-provider.js\";\nexport {\n useSuperblocksGroups,\n useSuperblocksUser,\n useSuperblocksProfiles,\n getAppMode,\n} from \"./internal-details/superblocks-context.js\";\n\n// User-facing components\nexport { App } from \"./user-facing/components/app/index.jsx\";\nexport {\n registerComponent,\n type PropertiesPanelDefinition,\n} from \"./user-facing/components/custom/register-custom-component.js\";\nexport { PageNotFound } from \"./user-facing/error-pages/page-not-found.jsx\";\nexport { RouteLoadError } from \"./internal-details/internal-components/route-load-error.jsx\";\n\nexport { useApiStateful as useApi } from \"./internal-details/use-api.js\";\n\n// User-facing types\nexport {\n Prop,\n Section,\n PropsCategory,\n} from \"./user-facing/properties-panel/props-builder.js\";\nexport { tailwindStylesCategory } from \"./user-facing/properties-panel/mixins/styles-category.js\";\n\n// TODO: Cleanup (remove Dim inside Property)\nexport { Property } from \"@superblocksteam/library-shared\";\nexport type { EditorConfig } from \"@superblocksteam/library-shared\";\nexport type {\n EditorTemplate,\n CreationContext,\n} from \"./internal-details/sb-wrapper.jsx\";\n\n// TODO: Move these to the library-shared package\nexport type {\n FromChildToParentMessageTypes,\n FromChildToParentMessageTypesMap,\n FromParentToChildMessageTypes,\n FromParentToChildMessageTypesMap,\n} from \"./internal-details/lib/types.js\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuFA,MAAa,6BACX,aACA,2BACuC;CACvC,MAAM,OACJ,OAAOA,gBAAc,WACjBA,cACAA,YAAU,eAAeA,YAAU;AAEzC,KAAI,CAAC,KACH,OAAM,IAAI,MACR,iFAAiFA,cAClF;CAGH,MAAM,eAAe,uBAAuBC,uBAAqB;CAGjE,MAAM,cAAc,CAAC,CAAC,aAAa,MAChC,MAAM,EAAE,SAAS,cAAc,EAAE,aAAc,MACjD;AAED,oBAAU,yBAAyB;AACjC,gBAAc,CAAC,uBAAuB,wBACpC,MACAA,uBACD;GACD;AAEF,oBAAU,kBAAkB,aAC1B,MACAD,aACAC,uBACD;AACD,oBAAU,kBAAkB,gBAAgB,MAAM,gBAAgB,EAAE,CAAC;CAErE,MAAMC,sBAAoC,EAAE;AAG5C,KAAI,aAAa;AACf,sBAAoB,cAAc;AAClC,qBAAU,kBAAkB,gBAAgB,MAAM,oBAAoB;;CAIxE,MAAMC,qBAAyD;EAC7D,oBACE,mBACuC;GACvC,MAAMC,UAAmB,eAAe,WAAW;IACjD,aAAa;IACb,UAAU;IACX;AACD,sBAAU,kBAAkB,kBAAkB,MAAM;IAClD,GAAG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