@superblocksteam/library 2.0.149 → 2.0.150-next.1

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.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"root-store-CkTnQd84.js","names":["exhaustiveCheck","SuccessIcon","ErrorIcon","InfoIcon","WarningIcon","context","ApiHmrTracker","superblocksContext"],"sources":["../src/edit-mode/get-edit-store.ts","../src/lib/user-facing/properties-panel/properties-panel-definition.ts","../src/lib/user-facing/properties-panel/props-builder.ts","../src/lib/user-facing/properties-panel/create-managed-props-list.ts","../src/lib/internal-details/is-edit-mode.ts","../src/lib/utils/clean-object.ts","../src/lib/internal-details/lib/iframe.ts","../src/edit-mode/base-editor-bridge.ts","../src/edit-mode/message-queue.ts","../src/edit-mode/superblocks-editor-bridge.ts","../src/lib/internal-details/location-store.ts","../src/lib/user-facing/assets/icons/system-danger.svg","../src/lib/user-facing/assets/icons/system-error.svg","../src/lib/user-facing/assets/icons/system-info.svg","../src/lib/user-facing/assets/icons/system-success.svg","../src/lib/user-facing/styling/colors.ts","../src/lib/user-facing/themes/classnames.ts","../src/lib/user-facing/utils/notification.tsx","../src/lib/utils/generate-id.ts","../src/lib/internal-details/embed-store.ts","../src/lib/internal-details/scope/types.ts","../src/lib/internal-details/superblocks-context.tsx","../src/lib/internal-details/lib/resolve-id-singleton.ts","../src/lib/internal-details/lib/features/api-hmr-tracker.ts","../src/lib/tracing/context-utils.ts","../src/lib/internal-details/lib/features/api-utils.ts","../src/lib/internal-details/lib/features/file-utils.ts","../src/lib/internal-details/lib/features/url-utils.ts","../src/lib/internal-details/lib/features/api-store.ts","../src/lib/internal-details/lib/evaluator/sanitize-object.ts","../src/edit-mode/mobx-sync/create-patch.ts","../src/edit-mode/mobx-sync/deep-observe.ts","../src/edit-mode/mobx-sync/mobx-editor-sync.ts","../src/lib/internal-details/lib/features/type-defs-utils.ts","../src/lib/internal-details/lib/features/component-registry.ts","../src/lib/internal-details/lib/root-store.ts"],"sourcesContent":["import type { EditStore } from \"./edit-store.js\";\n\n/**\n * Get the global EditStore instance\n * @returns The EditStore instance\n */\n\nexport function getEditStore(): EditStore {\n if (\n !window.__SUPERBLOCKS_EDITOR_HOOK__ ||\n !window.__SUPERBLOCKS_EDITOR_HOOK__.isInitialized\n ) {\n throw new Error(\"EditStore not initialized\");\n }\n return (window as any).__SUPERBLOCKS_EDITOR_HOOK__;\n}\n","import type {\n PropertiesPanelDefinition,\n PropertiesPanelSectionDefinition,\n WidgetPropertyDefinition,\n} from \"@superblocksteam/library-shared/props\";\n\nimport { type Section, type Prop, CompositeProp } from \"./props-builder.js\";\n\nfunction createPropertiesPanelDefinition(\n sections: Record<string, Section>,\n componentProps: Record<string, unknown>,\n): PropertiesPanelDefinition {\n const sectionDefs: Array<PropertiesPanelSectionDefinition> = [];\n\n const getSectionChildren = (\n propDefinitions: Partial<Record<string, Prop<any, any>>>,\n parentPath: string,\n ) => {\n const properties: WidgetPropertyDefinition<any>[] = [];\n\n /**\n * There are three ways we can display a Composite prop:\n * 1. Prop control + popover panel (e.g: TextStyle)\n * 2. Prop control (e.g: Border)\n * 3. Inline, without a prop control (e.g: Search prop on Table, which contains backgroundColor, borderRadius, etc.)\n *\n * isCompositeWithInlineNestedProps is used to determine if a prop is of type (3).\n */\n const isCompositeWithInlineNestedProps = (\n prop: Prop<any, any>,\n fullPath: string,\n ): prop is InstanceType<typeof CompositeProp<any>> => {\n if (\n !(prop instanceof CompositeProp) ||\n !prop.hasPropertiesPanelDisplay()\n ) {\n return false;\n }\n\n const displayMode = prop.propertiesPanelChildrenDisplayMode();\n if (!displayMode) {\n return false;\n }\n\n const resolvedDisplayMode =\n typeof displayMode === \"function\"\n ? displayMode(componentProps, fullPath)\n : displayMode;\n\n return resolvedDisplayMode?.type === \"inline\";\n };\n\n for (const [name, prop] of Object.entries(propDefinitions)) {\n if (!prop) continue;\n const fullPath = parentPath ? `${parentPath}.${name}` : name;\n\n if (isCompositeWithInlineNestedProps(prop, fullPath)) {\n // For case (3) we dive into the composite props, and treat nested props as regular props\n const inlinePropertiesDefs = getSectionChildren(\n prop.nestedProps,\n fullPath,\n );\n properties.push(...inlinePropertiesDefs);\n } else if (prop.hasPropertiesPanelDisplay()) {\n // For case (1) and (2) we do not dive into the composite props for panel purposes\n // because we will want to write the entire composite prop as a single update\n // for example, in the JSX if the user updates the \"topLeft\" property of a\n // \"borderRadius\" composite prop, we want to update the \"borderRadius\" prop\n // as a whole, not just the \"topLeft\" property\n\n const def = prop.setName(fullPath).toDefinition(componentProps);\n if (def) {\n properties.push(def);\n }\n }\n }\n\n return properties;\n };\n\n for (const section of Object.values(sections)) {\n const children = getSectionChildren(section.props, \"\");\n if (children.length === 0) {\n continue;\n }\n sectionDefs.push({\n name: section.name,\n category: section.category,\n children,\n showHeader: section.propertiesPanelConfig.showHeader,\n isDefaultOpen: section.propertiesPanelConfig.isDefaultOpen,\n headerType: section.propertiesPanelConfig.headerType,\n subHeader: section.propertiesPanelConfig.subHeader,\n });\n }\n\n return { sections: sectionDefs };\n}\n\nexport { createPropertiesPanelDefinition };\n","import type { ReactNode } from \"react\";\n\nimport type { EvaluateOrValueComputedArgs } from \"@superblocksteam/library-shared\";\nimport {\n type ControlType,\n type DataType,\n type DataTypeString,\n type PropertiesPanelDefinition,\n type PropertiesPanelDisplay,\n type PropertyForData,\n type WidgetPropertyDefinition,\n type Relation,\n PropsCategory,\n InputType,\n} from \"@superblocksteam/library-shared/props\";\nimport type {\n Callback,\n EvaluatedPropertiesPanelDisplay,\n HeaderType,\n} from \"@superblocksteam/library-shared/props\";\nimport type { Entity } from \"@superblocksteam/library-shared/types\";\n\nimport type {\n InputProp,\n SingleInputProp,\n EntityFunction,\n} from \"../../internal-details/lib/evaluator/entity-types.js\";\nimport type { InjectedProps } from \"../../internal-details/sb-wrapper.jsx\";\nimport type { SbComponentProps } from \"./../component-base/sb-component.js\";\nimport { createManagedPropsList } from \"./create-managed-props-list.js\";\nimport { createPropertiesPanelDefinition } from \"./properties-panel-definition.js\";\n\ntype Exact<T, Shape> = T extends Shape\n ? Exclude<keyof T, keyof Shape> extends never\n ? T\n : never\n : never;\n\nfunction mergeRelations(\n existingRelations: Relation[][],\n relations: Relation[][],\n): Relation[][] {\n if (!existingRelations || existingRelations.length === 0) {\n return relations;\n }\n if (!relations || relations.length === 0) {\n return existingRelations;\n }\n const mergedRelations =\n existingRelations && existingRelations.length > 0\n ? existingRelations.flatMap((existing) =>\n relations.map((relation) => [...existing, ...relation]),\n )\n : relations;\n return mergedRelations;\n}\n\ntype ManagedProp<T extends DataType = DataType> = PropertyForData<T> & {\n default?: SingleInputProp<T>;\n defaultOnAdd?: SingleInputProp<T>;\n\n /**\n * Controls binding nesting behavior:\n * - true: Allows bindings to be nested at any depth within this property\n * - false: Only allows bindings at the top level (unless the property is composite)\n */\n nestedBindings?: boolean;\n\n /**\n * Indicates this property should be evaluated per-context (e.g., per-row in tables)\n * When true, the property value will be evaluated for each context with access to context variables\n */\n contextual?: boolean;\n computedArgs?: EvaluateOrValueComputedArgs;\n};\n\ntype ManagedPropsList = Array<\n ManagedProp & {\n propertiesPanelDisplay?: PropertiesPanelDisplay<any>;\n }\n>;\n\n/**\n * Merges shared and variant properties for union types without creating intersections\n * Variant properties override shared properties with the same key\n */\ntype MergeUnionVariant<\n SHARED extends Record<string, Prop<any, any>>,\n VARIANT extends Record<string, Prop<any, any>>,\n> = Omit<SHARED, keyof VARIANT> & VARIANT;\n\n/**\n * Converts a union type to an intersection type\n * Used to merge multiple section props into a single props type\n */\ntype UnionToIntersection<U> = (U extends any ? (x: U) => void : never) extends (\n x: infer I extends U,\n) => void\n ? I\n : never;\n\n/**\n * Controls how default values affect property optionality\n * - RequiredIfDefault: Properties with default values become required\n * - AlwaysOptional: All properties become optional regardless of defaults\n */\ntype DefaultValueBehavior = \"RequiredIfDefault\" | \"AlwaysOptional\";\n\n/**\n * Extracts the concrete type from a property definition\n *\n * For evaluated props: returns the actual value type\n *\n * For non-evaluated props: returns InputProp<ValueType>\n */\n/**\n * Extracts the concrete type from a property definition\n * Enhanced to handle contextual properties\n */\ntype ExtractPropType<\n T,\n DefaultsBehavior extends DefaultValueBehavior,\n IsEvaluated extends boolean,\n> =\n T extends Record<string, Prop<any, any, any>>\n ? ExtractProps<T, DefaultsBehavior, IsEvaluated>\n : T extends RecordProp<infer U>\n ? Record<string, ExtractProps<U, DefaultsBehavior, IsEvaluated>>\n : T extends CompositeProp<infer U>\n ? IsEvaluated extends true\n ? ExtractProps<U, DefaultsBehavior, IsEvaluated>\n : InputProp<ExtractProps<U, DefaultsBehavior, true>>\n : T extends UnionProp<infer SHARED, infer VARIANTS>\n ? VARIANTS extends readonly any[]\n ? {\n [I in keyof VARIANTS]: ExtractProps<\n MergeUnionVariant<SHARED, VARIANTS[I]>,\n DefaultsBehavior,\n IsEvaluated\n >;\n }[number]\n : never\n : T extends Prop<infer V, infer _HasDefault, infer ContextualProps>\n ? IsEvaluated extends true\n ? ContextualProps extends undefined\n ? V extends Callback\n ? (...args: any[]) => Promise<void>\n : V\n : ContextualProps extends any[]\n ? (...args: ContextualProps) => V\n : InputProp<V>\n : InputProp<V>\n : never;\n/**\n * Extracts a flat props object from a properties definition\n * Handles optionality based on DefaultValueBehavior\n */\ntype ExtractProps<\n T,\n DefaultsBehavior extends DefaultValueBehavior,\n IsEvaluated extends boolean,\n> =\n T extends Record<string, Section>\n ? ExtractProps<MergeSections<T>, DefaultsBehavior, IsEvaluated>\n : T extends SectionPropRecord\n ? DefaultsBehavior extends \"AlwaysOptional\"\n ? {\n [K in keyof T as T[K] extends Prop<any, any, any>\n ? K\n : never]?: ExtractPropType<T[K], DefaultsBehavior, IsEvaluated>;\n }\n : {\n [K in keyof T as T[K] extends Prop<any, infer HasDefault, any>\n ? HasDefault extends true\n ? K\n : never\n : never]: ExtractPropType<T[K], DefaultsBehavior, IsEvaluated>;\n } & {\n [K in keyof T as T[K] extends Prop<any, infer HasDefault, any>\n ? HasDefault extends false\n ? K\n : never\n : never]?: ExtractPropType<T[K], DefaultsBehavior, IsEvaluated>;\n }\n : never;\n\n/**\n * Handles non Prop types, aka our default types and CSS props\n */\ntype RawPropsToExternal<T = Record<string, unknown>> = {\n [K in keyof T as undefined extends T[K] ? never : K]: SingleInputProp<T[K]>;\n} & {\n [K in keyof T as undefined extends T[K] ? K : never]?: SingleInputProp<\n Exclude<T[K], undefined>\n >;\n};\n\ntype SectionPropertiesPanelConfig = {\n showHeader?: boolean;\n isDefaultOpen?: boolean;\n headerType?: HeaderType;\n subHeader?: string;\n};\n\n/**\n * Merges all sections in a properties definition into a single props type\n */\ntype MergeSections<\n T extends Record<string, Section>,\n Merged = UnionToIntersection<T[keyof T]>,\n> = Merged extends Section<any, infer U> ? U : never;\n\n/**\n * Identical to InternalProps but without the base props\n */\ntype EntityProps<\n Definition extends PropertiesDefinition,\n MergedSections = MergeSections<Definition>,\n> = ExtractProps<MergedSections, \"RequiredIfDefault\", true>;\n\n/**\n * Internal props used by the component implementation\n * - Properties with defaults are required\n * - Properties are fully evaluated to their final types\n */\ntype InternalProps<\n Definition extends PropertiesDefinition,\n FlattenedProps = EntityProps<Definition>,\n BaseProps = Omit<SbComponentProps, keyof FlattenedProps>,\n> = FlattenedProps & BaseProps & InjectedProps;\n\n/**\n * External props exposed to component consumers\n * - All properties are optional regardless of defaults\n * - Properties accept InputProp values (bindings/functions)\n */\ntype ExternalProps<\n Definition extends PropertiesDefinition,\n MergedSections = MergeSections<Definition>,\n FlattenedProps = ExtractProps<MergedSections, \"AlwaysOptional\", false>,\n BaseProps = Omit<SbComponentProps, keyof FlattenedProps>,\n> = FlattenedProps & RawPropsToExternal<BaseProps>;\n\ntype PropertiesDefinition = Record<string, Section>;\n\ntype SectionDefinition<T extends Record<string, Prop<any, any>>> = {\n props: T;\n showHeader?: boolean;\n isDefaultOpen?: boolean;\n headerType?: HeaderType;\n subHeader?: string;\n};\n\nfunction getChildren(\n input: CompositeInputs,\n path: string,\n props: Record<string, unknown>,\n) {\n function getChildrenFromSection(section: Section) {\n return Object.keys(section.props).reduce(\n (acc, key) => {\n const prop = section.props[key];\n if (!prop) return acc;\n const definition = prop.setName(path + \".\" + key).toDefinition(props);\n if (definition) {\n acc[key] = definition;\n }\n return acc;\n },\n {} as Record<string, WidgetPropertyDefinition<DataType>>,\n );\n }\n\n let children: Record<string, WidgetPropertyDefinition<DataType>>;\n if (input instanceof Section) {\n // Case 1: content is a Section\n children = getChildrenFromSection(input);\n } else if (Object.values(input).every((c) => c instanceof Section)) {\n // Case 2: content is a Record<string, Section>\n children = Object.values(input).reduce((acc, section) => {\n return { ...acc, ...getChildrenFromSection(section) };\n }, {});\n } else {\n // Case 3: content is a Record<string, Prop<any, any, any>>\n children = Object.fromEntries(\n Object.entries(input).map(([key, prop]) => {\n return [key, prop.setName(path + \".\" + key).toDefinition(props)];\n }),\n );\n }\n return children;\n}\n\nexport type SectionPropRecord<Props = Record<string, any>> = Partial<{\n [K in keyof Props]: Prop<Props[K], any>;\n}>;\n\nclass Section<\n TProps = any, // Component props type for validation\n T extends SectionPropRecord<TProps> = SectionPropRecord<TProps>,\n> {\n props: T = {} as T;\n\n propertiesPanelConfig: SectionPropertiesPanelConfig = {\n showHeader: true,\n isDefaultOpen: true,\n };\n\n constructor(readonly category: PropsCategory) {}\n\n static category<Props = any>(category: PropsCategory) {\n return new Section<Props, SectionPropRecord<Props>>(category);\n }\n\n children<\n INP extends\n | SectionPropRecord<TProps>\n | CompositeProp<any>\n | UnionProp<any, any>,\n OUT extends INP extends CompositeProp<infer CU>\n ? CU\n : INP extends UnionProp<infer SHARED, infer VARIANTS>\n ? VARIANTS extends readonly any[]\n ? {\n [I in keyof VARIANTS]: MergeUnionVariant<SHARED, VARIANTS[I]>;\n }[number]\n : never\n : INP,\n >(\n props: INP extends CompositeProp<any> | UnionProp<any, any>\n ? INP\n : Exact<INP, SectionPropRecord<TProps>>,\n ): Section<TProps, T & OUT> {\n if (props instanceof CompositeProp || props instanceof RecordProp) {\n this.props = { ...this.props, ...props.getProps() } as unknown as T & OUT;\n } else if (props instanceof UnionProp) {\n this.props = { ...this.props, ...props.getProps() } as unknown as T & OUT;\n } else {\n this.props = { ...this.props, ...props } as unknown as T & OUT;\n }\n return this as unknown as Section<TProps, T & OUT>;\n }\n\n add = this.children;\n\n propertiesPanel(config: Omit<SectionDefinition<any>, \"props\">) {\n this.propertiesPanelConfig = {\n ...this.propertiesPanelConfig,\n ...config,\n };\n return this;\n }\n\n get name() {\n switch (this.category) {\n case PropsCategory.Content:\n return \"Content\";\n case PropsCategory.Routing:\n return \"Routing\";\n case PropsCategory.Interaction:\n return \"Interaction\";\n case PropsCategory.Layout:\n return \"Layout\";\n case PropsCategory.Appearance:\n return \"Appearance\";\n case PropsCategory.Permissions:\n return \"Permissions\";\n case PropsCategory.EventHandlers:\n return \"Actions\";\n case PropsCategory.Styles:\n return \"Styles\";\n case PropsCategory.Uncategorized:\n return \"Uncategorized\";\n default:\n return \"Uncategorized\";\n }\n }\n}\n\nclass Prop<\n Type extends DataType,\n _HasDefault extends boolean = false,\n _ContextualArgs extends\n | any[]\n | undefined\n | ((entity: Entity) => any[] | undefined) = undefined,\n> {\n protected prop: ManagedProp<Type>;\n\n /**\n * Relations are an array of arrays\n * each sub-array is AND requirements, and each element is an OR requirement\n */\n protected relations: Relation[][] = [];\n\n protected constructor(typeString: DataTypeString) {\n this.prop = {\n path: \"\",\n dataType: typeString,\n };\n }\n\n static unset(): Prop<undefined> {\n return new Prop(\"any\") as Prop<undefined>;\n }\n\n static string<T extends string>(): Prop<T> {\n return new Prop(\"string\") as Prop<T>;\n }\n\n static number<T extends number>(): Prop<T> {\n return new Prop(\"number\") as Prop<T>;\n }\n\n static boolean<T extends boolean>(): Prop<T> {\n return new Prop(\"boolean\") as Prop<T>;\n }\n\n static array<T>(): Prop<Array<T>> {\n return new Prop(\"array\") as Prop<Array<T>>;\n }\n\n static any<T = any>(): Prop<T> {\n return new Prop(\"any\") as Prop<T>;\n }\n\n static jsx<T extends ReactNode>(): Prop<T> {\n return new Prop(\"jsx\") as Prop<T>;\n }\n\n static literal<T extends Readonly<string | number | boolean>>(\n value: T,\n ): Prop<T, true> {\n switch (typeof value) {\n case \"string\":\n return Prop.string().default(value) as Prop<T, true>;\n case \"number\":\n return Prop.number().default(value) as Prop<T, true>;\n case \"boolean\":\n return Prop.boolean().default(value) as Prop<T, true>;\n default: {\n const exhaustiveCheck: never = value;\n throw new Error(`Invalid literal value: ${exhaustiveCheck}`);\n }\n }\n }\n\n static eventHandler(): Prop<any> {\n return new Prop(\"eventHandler\") as Prop<any>;\n }\n\n static function<ARGS extends any[] = any[], RETURN = any>(\n implementation: EntityFunction<ARGS, RETURN>,\n ) {\n return new FunctionProp(implementation);\n }\n\n /**\n * Creates a composite property, which is a property that contains nested properties. For example,\n * the following composite property:\n *\n * ```ts\n * const prop = Prop.composite({\n * name: Prop.string(),\n * age: Prop.number(),\n * });\n * ```\n *\n * is equivalent to the following type:\n *\n * ```ts\n * type Prop = {\n * name: string;\n * age: number;\n * };\n * ```\n */\n static composite<T extends CompositeInputs>(props: T) {\n return new CompositeProp<T>(props);\n }\n\n /**\n * Creates a record property, which is a record that maps string keys to the nestedproperties. For example,\n * the following record property:\n *\n * ```ts\n * const prop = Prop.record({\n * name: Prop.string(),\n * age: Prop.number(),\n * });\n * ```\n *\n * is equivalent to the following type:\n *\n * ```ts\n * type Prop = Record<string, {\n * name: string;\n * age: number;\n * }>;\n * ```\n */\n static record<T extends CompositeInputs>(props: T) {\n return new RecordProp<T>(props);\n }\n\n static union<\n SHARED extends Record<string, Prop<unknown, boolean>>,\n VARIANTS extends UnionVariant<SHARED>[] = UnionVariant<SHARED>[],\n >(props: { shared: SHARED; variants: VARIANTS }) {\n return new UnionProp<SHARED, VARIANTS>(props.shared, props.variants);\n }\n\n default(de: SingleInputProp<DataType>): Prop<Type, true> {\n this.prop.default = de;\n if (\n this.prop.propertiesPanelDisplay &&\n this.prop.propertiesPanelDisplay.defaultValue === undefined\n ) {\n this.prop.propertiesPanelDisplay.defaultValue = de;\n }\n return this as unknown as Prop<Type, true>;\n }\n\n contextual<TContext extends any[] | undefined = any[]>(\n computedArgs?: EvaluateOrValueComputedArgs,\n ) {\n this.prop.contextual = true;\n this.prop.computedArgs = computedArgs;\n return this as Prop<Type, _HasDefault, TContext>;\n }\n\n setName(name: string) {\n this.prop.path = name;\n return this;\n }\n\n propertiesPanel<CT extends ControlType>(\n schema: Omit<\n Partial<PropertiesPanelDisplay<Type, CT>>,\n \"isTriggerProperty\"\n >,\n ) {\n // map dataType to control type\n let baseControlType: ControlType;\n let isJSConvertible = true;\n let isTriggerProperty = false;\n let inputType: InputType | undefined;\n switch (this.prop.dataType) {\n case \"string\":\n baseControlType = \"INPUT_TEXT\";\n break;\n case \"number\":\n baseControlType = \"INPUT_TEXT\";\n inputType = InputType.NUMBER;\n break;\n case \"array\":\n baseControlType = \"INPUT_TEXT\";\n break;\n case \"boolean\":\n baseControlType = \"SWITCH\";\n break;\n case \"eventHandler\":\n baseControlType = \"EVENT_HANDLER\";\n isJSConvertible = false;\n isTriggerProperty = true;\n break;\n case \"jsx\":\n baseControlType = \"JSX\";\n break;\n case \"any\":\n default:\n baseControlType = \"INPUT_JS_EXPR\";\n break;\n }\n\n const propertiesPanelDisplay = {\n controlType: baseControlType,\n isJSConvertible,\n isTriggerProperty,\n defaultValue: schema.defaultValue ?? this.prop.default,\n defaultOnAdd: this.prop.propertiesPanelDisplay?.defaultOnAdd,\n inputType,\n ...schema,\n } as PropertiesPanelDisplay<Type>;\n\n this.prop.propertiesPanelDisplay = propertiesPanelDisplay;\n return this;\n }\n\n setDisplayProperty<K extends keyof PropertiesPanelDisplay<Type>>(\n property: K,\n value: PropertiesPanelDisplay<Type>[K],\n ) {\n if (!this.prop.propertiesPanelDisplay) return this;\n this.prop.propertiesPanelDisplay[property] = value;\n return this;\n }\n\n docs(docs: Exclude<PropertyForData<DataType>[\"docs\"], undefined>) {\n this.prop.docs = docs;\n return this;\n }\n\n build() {\n return this.prop;\n }\n\n toDefinition(\n props: Record<string, unknown>,\n ): WidgetPropertyDefinition<DataType> | undefined {\n const evaluatedProperties = Object.entries(\n this.prop.propertiesPanelDisplay ?? {},\n ).reduce(\n (acc, [key, value]) => {\n if (typeof value === \"function\") {\n try {\n // TODO(mark): type this like is used to take in entity and scopedState\n acc[key] = value.bind(props)(this.prop.path);\n } catch (e) {\n console.error(`Error evaluating property ${key}:`, e);\n }\n }\n return acc;\n },\n {} as Record<string, unknown>,\n ) as Partial<EvaluatedPropertiesPanelDisplay<Type>>;\n\n if (evaluatedProperties.isVisible === false) {\n return undefined;\n }\n\n const propertiesPanelDisplay = {\n ...this.prop.propertiesPanelDisplay,\n ...evaluatedProperties,\n } as EvaluatedPropertiesPanelDisplay<Type>;\n\n if (\"treatDefaultAsNull\" in propertiesPanelDisplay) {\n if (propertiesPanelDisplay.treatDefaultAsNull) {\n if (propertiesPanelDisplay.defaultOnAdd === undefined) {\n propertiesPanelDisplay.defaultOnAdd =\n propertiesPanelDisplay.defaultValue;\n }\n\n propertiesPanelDisplay.defaultValue = undefined;\n }\n }\n\n let panelConfig: PropertiesPanelDefinition | undefined;\n\n const childrenDisplay = propertiesPanelDisplay?.childrenDisplayMode;\n const isPopover = childrenDisplay?.type === \"popover\";\n if (isPopover) {\n if (!(this instanceof CompositeProp || this instanceof RecordProp)) {\n console.error(this);\n throw new Error(\n \"Only composite properties can be used in popover properties at the moment\",\n );\n }\n const content = this.getProps();\n const { type, ...rest } = childrenDisplay;\n\n let contentDef: Record<string, Section>;\n if (content instanceof Section) {\n // Case 1: content is a Section\n contentDef = { content };\n } else if (Object.values(content).every((c) => c instanceof Section)) {\n // Case 2: content is a Record<string, Section>\n contentDef = content as Record<string, Section>;\n } else {\n // Case 3: content is a Record<string, Prop<any, any, any>>\n contentDef = {\n content: Section.category(PropsCategory.Content)\n .propertiesPanel({\n showHeader: false,\n })\n .children(content as Record<string, Prop<any, any>>),\n };\n }\n panelConfig = {\n ...createPropertiesPanelDefinition(contentDef, props),\n ...rest,\n };\n }\n if (this.prop.computedArgs) {\n propertiesPanelDisplay.computedArgs =\n typeof this.prop.computedArgs === \"function\"\n ? this.prop.computedArgs(props)\n : this.prop.computedArgs;\n }\n\n const propertiesPanelDisplayWithPanelConfig = {\n ...propertiesPanelDisplay,\n ...(panelConfig && { panelConfig }),\n };\n\n return {\n path: this.prop.path,\n dataType: this.prop.dataType,\n relations: this.relations,\n propertiesPanelDisplay: propertiesPanelDisplayWithPanelConfig,\n };\n }\n\n getRelations() {\n return this.relations;\n }\n\n dependsOn(relations: Relation[][]) {\n this.relations = relations;\n return this;\n }\n\n hasPropertiesPanelDisplay() {\n return this.prop.propertiesPanelDisplay !== undefined;\n }\n\n get type() {\n return this.prop.dataType;\n }\n\n get path() {\n return this.prop.path;\n }\n}\n\ntype CompositeInputs =\n | Record<string, Section>\n | Section\n | Record<string, Prop<unknown, boolean>>;\n\n/**\n * See {@link Prop.composite}\n */\nclass CompositeProp<T extends CompositeInputs> extends Prop<unknown, boolean> {\n typeString = \"composite\" as const;\n nestedProps: T;\n\n constructor(props: T) {\n super(\"composite\");\n this.nestedProps = props;\n }\n\n getProps() {\n return this.nestedProps;\n }\n\n toDefinition(\n props: Record<string, unknown>,\n ): WidgetPropertyDefinition<DataType> | undefined {\n const definition = super.toDefinition(props);\n if (!definition) {\n return undefined;\n }\n return {\n ...definition,\n children: getChildren(this.nestedProps, this.prop.path, props),\n };\n }\n\n propertiesPanelChildrenDisplayMode() {\n return this.prop.propertiesPanelDisplay?.childrenDisplayMode;\n }\n}\n\n/**\n * See {@link Prop.record}\n */\nclass RecordProp<T extends CompositeInputs> extends Prop<\n Record<string, any>,\n boolean\n> {\n typeString = \"recordOf\" as const;\n nestedProps: T;\n\n constructor(props: T) {\n super(\"recordOf\");\n this.nestedProps = props;\n }\n\n getProps() {\n return this.nestedProps;\n }\n\n toDefinition(\n props: Record<string, unknown>,\n ): WidgetPropertyDefinition<DataType> | undefined {\n const definition = super.toDefinition(props);\n if (!definition) {\n return undefined;\n }\n\n return {\n ...definition,\n children: getChildren(this.nestedProps, this.prop.path, props),\n };\n }\n}\n\ninterface ActionPanel {\n arguments?: Record<string, Prop<any>>;\n}\n\nclass FunctionProp<ARGS extends any[] = any[], RETURN = any> extends Prop<\n EntityFunction<ARGS, RETURN>,\n true\n> {\n typeString = \"function\" as const;\n private _actionPanel: ActionPanel | undefined;\n\n constructor(implementation: EntityFunction<ARGS, RETURN>) {\n super(\"function\");\n this.default(implementation);\n }\n\n actionPanel(panel?: ActionPanel) {\n this._actionPanel = panel || {};\n return this;\n }\n\n getActionPanel() {\n return this._actionPanel;\n }\n}\n\ntype UnionVariant<SHARED extends Record<string, Prop<any>>> = {\n [K in keyof SHARED]: Prop<any>;\n};\n\nclass UnionProp<\n SHARED extends Record<string, Prop<unknown, boolean>>,\n VARIANTS extends UnionVariant<SHARED>[] = UnionVariant<SHARED>[],\n _OUTPUT = VARIANTS extends readonly any[]\n ? {\n [I in keyof VARIANTS]: SHARED & VARIANTS[I];\n }[number]\n : never,\n> extends Prop<any> {\n typeString = \"union\" as const;\n shared: SHARED;\n variants: VARIANTS;\n\n constructor(shared: SHARED, variants: VARIANTS) {\n super(\"any\");\n this.shared = shared;\n this.variants = variants;\n }\n\n getProps() {\n const sharedKeys = Object.keys(this.shared);\n const variants: UnionVariant<typeof this.shared>[] = this.variants;\n const preMergeRelationsMap = variants.reduce(\n (acc, v) => {\n Object.entries(v).forEach(([key, prop]) => {\n const existingRelations = acc[key] ?? [];\n const newRelations = prop.getRelations() ?? [];\n acc[key] = [...existingRelations, ...newRelations];\n });\n return acc;\n },\n {} as Record<string, Relation[][]>,\n );\n const mergedVariants = variants.reduce(\n (acc, v) => {\n // These are the constants that are shared between the variant and the shared props\n const variantConstants = Object.entries(v).filter(([key]) =>\n sharedKeys.includes(key),\n );\n // These are the relations that are unique to the variant\n // For example, shared has style and variant has style == \"rounded\"\n // Then the relations for the variant are the { key: style value: \"rounded\" }\n const relations = variantConstants.map(([key, prop]) => {\n // check if this v already has a relation for his key\n return {\n key,\n value: prop.build().default,\n };\n });\n // Now we filter out the shared keys and add dependencies to the variant\n const filteredVariant = Object.fromEntries(\n Object.entries(v)\n .filter(([key]) => !sharedKeys.includes(key))\n .map(([key, prop]) => {\n const existingRelations = prop?.getRelations() ?? [];\n const preMergeRelations = preMergeRelationsMap[key];\n const existingNonPreMergeRelations = existingRelations.filter(\n (r) => !preMergeRelations.some((p) => p === r),\n );\n // within a union, the conditions are OR'ed, but across unions, the conditions are AND'ed\n const newProp = prop.dependsOn([\n ...existingNonPreMergeRelations,\n ...mergeRelations(preMergeRelations, [relations]),\n ]);\n\n // If this property already exists in acc, merge the relations using OR logic\n if (acc[key]) {\n const existingPropRelations = acc[key].getRelations() ?? [];\n const newPropRelations = newProp.getRelations() ?? [];\n\n const seenHashes = new Set<string>();\n const uniqueRelations = [\n ...existingPropRelations,\n ...newPropRelations,\n ].filter((relationGroup) => {\n const hash = relationGroup\n .map((r) => `${r.key}:${String(r.value)}`)\n .sort()\n .join(\"|\");\n if (seenHashes.has(hash)) {\n return false;\n }\n seenHashes.add(hash);\n return true;\n });\n\n return [key, acc[key].dependsOn(uniqueRelations)];\n }\n\n return [key, newProp];\n }),\n );\n\n return { ...acc, ...filteredVariant };\n },\n {} as Record<string, Prop<any>>,\n );\n return { ...this.shared, ...mergedVariants };\n }\n}\n\nexport type {\n ManagedProp,\n ManagedPropsList,\n InternalProps,\n ExternalProps,\n EntityProps,\n PropertiesDefinition,\n};\n\nexport {\n Prop,\n CompositeProp,\n RecordProp,\n UnionProp,\n Section,\n PropsCategory,\n createManagedPropsList,\n};\n","import type { DataType } from \"@superblocksteam/library-shared/props\";\nimport type { ScopedState } from \"@superblocksteam/library-shared/types\";\n\nimport {\n Prop,\n CompositeProp,\n UnionProp,\n RecordProp,\n Section,\n} from \"./props-builder.js\";\nimport type { ManagedPropsList } from \"./props-builder.js\";\n\nexport const RECORD_PATH_IDENTIFIER = \"*\";\n\nfunction buildCompositeDefault(\n prop: Prop<any, false>,\n name: string,\n parentDefault?: Record<string, any>,\n) {\n const defaultThroughParent = parentDefault?.[name];\n const selfDefault = prop.build().default;\n // Honor parent default\n let propDefault = defaultThroughParent ?? selfDefault;\n if (!propDefault && typeof parentDefault === \"function\") {\n propDefault = function getNestedDefault(this: any, s: ScopedState) {\n return parentDefault.call(this, s)?.[name];\n };\n }\n return propDefault;\n}\n\nfunction buildPropLeafDefault(\n prop: Prop<any, false>,\n name: string,\n parentDefault?: Record<string, any>,\n) {\n const defaultThroughParent = parentDefault?.[name];\n const selfDefault = prop.build().default;\n // Honor self default\n let propDefault = selfDefault ?? defaultThroughParent;\n if (!propDefault && typeof parentDefault === \"function\") {\n propDefault = function getNestedDefault(this: any, s: ScopedState) {\n return parentDefault.call(this, s)?.[name];\n };\n }\n return propDefault;\n}\n\n/**\n * Core traversal function that walks through all properties in sections\n * and calls the provided callback for each leaf property.\n */\nfunction traverseProps(\n sections: Record<string, Section>,\n onProp: (\n prop: Prop<DataType>,\n fullPath: string,\n name: string,\n parentDefault?: Record<string, any>,\n ) => void,\n parentPath = \"\",\n) {\n const processProps = ({\n props,\n parentPath,\n parentDefault,\n }: {\n props: Partial<Record<string, Prop<DataType>>>;\n parentPath: string;\n parentDefault?: Record<string, any>;\n }) => {\n for (const [name, prop] of Object.entries(props)) {\n if (!prop) continue;\n const fullPath = parentPath ? `${parentPath}.${name}` : name;\n if (prop instanceof CompositeProp) {\n const compositeDefault = buildCompositeDefault(\n prop,\n name,\n parentDefault,\n );\n\n processProps({\n props: prop.nestedProps,\n parentPath: fullPath,\n parentDefault: compositeDefault,\n });\n } else if (prop instanceof RecordProp) {\n const recordPath = `${fullPath}.${RECORD_PATH_IDENTIFIER}`;\n processProps({\n props: prop.nestedProps,\n parentPath: recordPath,\n parentDefault: prop.build().default as any,\n });\n } else if (prop instanceof Section) {\n // the section path is opaque, it should not be part of a property path\n processProps({\n props: prop.props,\n parentPath,\n });\n } else if (prop instanceof UnionProp) {\n const sharedKeys = Object.keys(prop.shared);\n processProps({\n props: prop.shared,\n parentPath: fullPath,\n });\n\n for (const variant of prop.variants) {\n const variantWithoutSharedKeys = Object.fromEntries(\n Object.entries(variant).filter(\n ([key]) => !sharedKeys.includes(key),\n ),\n ) as Record<string, Prop<DataType, any>>;\n processProps({\n props: variantWithoutSharedKeys,\n parentPath: fullPath,\n });\n }\n } else if (prop instanceof Prop) {\n // Call the callback for each leaf property\n onProp(prop, fullPath, name, parentDefault);\n } else {\n console.warn(\"Invalid prop type\", { name, prop });\n }\n }\n };\n\n for (const section of Object.values(sections)) {\n processProps({\n props: section.props,\n parentPath,\n parentDefault: undefined,\n });\n }\n}\n\nfunction createManagedPropsList(\n sections: Record<string, Section>,\n parentPath = \"\",\n): ManagedPropsList {\n const managedPropsList: ManagedPropsList = [];\n\n traverseProps(\n sections,\n (prop, fullPath, name, parentDefault) => {\n let configuredProp = prop.setName(fullPath);\n\n const propDefault = buildPropLeafDefault(prop, name, parentDefault);\n if (propDefault !== undefined) {\n configuredProp = configuredProp.default(propDefault);\n }\n\n const builtProp = configuredProp.build();\n\n // Skip internal properties from managed props list\n // Internal properties are handled separately and not exposed/tracked\n if (builtProp.dataType === \"internal\") {\n return;\n }\n\n // TODO(code-mode): This spread is here because the fullPath is overwritten by other setName calls\n managedPropsList.push({ ...builtProp });\n },\n parentPath,\n );\n\n return managedPropsList;\n}\n\nexport { createManagedPropsList };\n","const getIsEditMode = () => {\n return (window as any)._SB_VIEW_MODE === \"dev\";\n};\n\nlet editMode: boolean | undefined;\n\nexport const isEditMode = () => {\n if (editMode === undefined) {\n editMode = getIsEditMode();\n }\n return editMode;\n};\n","import { toJS } from \"mobx\";\nimport { isValidElement } from \"react\";\n\nexport const isReactElement = (obj: any) => {\n return (\n obj &&\n (obj.$$typeof === Symbol.for(\"react.element\") ||\n isValidElement(obj) ||\n (typeof Node !== \"undefined\" && obj instanceof Node))\n );\n};\n\n/**\n * Check if an object is a Window object (including cross-origin windows)\n */\nconst isWindowObject = (obj: any): boolean => {\n if (!obj || typeof obj !== \"object\") {\n return false;\n }\n // Check if it's a Window without accessing properties that might throw SecurityError\n try {\n return obj instanceof Window || obj === window || obj?.window === obj;\n } catch {\n // If we get a SecurityError, it's likely a cross-origin window\n return true;\n }\n};\n\n/**\n * Cleans an object by removing proxy wrappers and filtering out functions.\n * This is useful for preparing objects for JSON serialization.\n */\nexport function cleanObject<T>(obj: T): unknown {\n // Don't try to process Window objects - they can cause SecurityError with cross-origin iframes\n if (isWindowObject(obj)) {\n return undefined;\n }\n\n // sometimes its a proxy in our managers\n try {\n obj = toJS(obj);\n } catch (error) {\n // If toJS throws (e.g., SecurityError from cross-origin access), skip this object\n if (error instanceof Error && error.name === \"SecurityError\") {\n return undefined;\n }\n // Re-throw other errors\n throw error;\n }\n\n // Remove functions\n if (!obj || typeof obj !== \"object\") {\n return typeof obj === \"function\" ? undefined : obj;\n }\n\n if (Array.isArray(obj)) {\n return obj.map(cleanObject).filter((item) => item !== undefined);\n }\n\n if (isReactElement(obj)) {\n return undefined;\n }\n\n return Object.entries(obj).reduce(\n (acc, [key, value]) => {\n // TODO: make this a bit more robust. a lot of theme objects are shared, so\n // using a seen set doesn't quite work, this just handles the case where we shove a\n // bind onto an entity\n if (obj === value || key === \"bind\") {\n return acc;\n }\n\n const cleaned = cleanObject(value);\n if (cleaned !== undefined) {\n acc[key] = cleaned;\n }\n return acc;\n },\n {} as Record<string, unknown>,\n );\n}\n","import { cleanObject } from \"../../utils/clean-object.js\";\nimport type {\n FromChildToParentMessageTypes,\n FromChildToParentMessageTypesMap,\n FromParentToChildMessageTypes,\n FromParentToChildMessageTypesMap,\n} from \"./types.js\";\n\nexport function isEmbeddedBySuperblocksFirstParty() {\n return typeof window !== \"undefined\" && window !== window.parent;\n}\n\n// TODO: window.opener for 'open in new tab' feature\nconst PARENT_REF =\n typeof window !== \"undefined\" && window !== window.parent\n ? window.parent\n : null;\nconst SELF_REF = typeof window !== \"undefined\" ? window : null;\n\n// Captured from the first authenticated inbound message so child→parent\n// postMessage calls can target the parent's exact origin instead of `\"*\"`.\n// `null` until an inbound message arrives — by which point any reply we send\n// (e.g. `app-websocket-connected`) has already been gated on `sb-init`.\nlet capturedParentOrigin: string | null = null;\n\nexport function getParentOrigin(): string | null {\n return capturedParentOrigin;\n}\n\nfunction parentMessageHandler(e: MessageEvent) {\n // Make sure the message is coming from either:\n // - The parent window\n // - The same window (for devbox)\n if (e.source !== PARENT_REF && e.source !== SELF_REF) return;\n\n if (capturedParentOrigin === null && e.origin) {\n capturedParentOrigin = e.origin;\n }\n\n const event = new SbIframeEventInternal(\n e.data.type as FromParentToChildMessageTypes,\n e.data,\n );\n iframeMessageHandler.dispatchEvent(event);\n}\n\nif (isEmbeddedBySuperblocksFirstParty() && PARENT_REF) {\n // eslint-disable-next-line @typescript-eslint/no-unused-expressions\n typeof window !== \"undefined\" &&\n window.addEventListener(\"message\", parentMessageHandler);\n}\n\n/**\n * @deprecated Use editorBridge instead\n *\n * IMPORTANT: For \"resolve-promise\" and \"reject-promise\" message types:\n * - callbackId MUST be at the top level of the message object\n * - payload contains the resolution value or error object\n * - Do NOT nest callbackId inside payload\n *\n * Example:\n * ```typescript\n * // ✅ Correct\n * sendMessageImmediately({\n * type: \"resolve-promise\",\n * callbackId: \"abc123\",\n * payload: { data: \"result\" }\n * });\n *\n * // ❌ Wrong\n * sendMessageImmediately({\n * type: \"resolve-promise\",\n * payload: { id: \"abc123\", data: \"result\" }\n * });\n * ```\n */\nexport function sendMessageImmediately<\n MT extends FromChildToParentMessageTypes,\n>(\n message: {\n type: MT;\n payload?: FromChildToParentMessageTypesMap[MT];\n [key: string]: any;\n },\n options?: {\n // For when you have debounced the sendMessage and want better stats\n overrideStartTime: number;\n },\n) {\n if (!PARENT_REF) {\n console.warn(\n \"PARENT_REF is not set, message not delivered. Message: \",\n message,\n );\n return;\n }\n\n message = cleanObject(message) as typeof message;\n\n if (isEmbeddedBySuperblocksFirstParty()) {\n if (!PARENT_REF) throw new Error(\"Parent is not set\");\n try {\n PARENT_REF.postMessage(\n {\n ...message,\n startTime: options?.overrideStartTime ?? +new Date(),\n },\n \"*\",\n );\n } catch (e) {\n console.error(\"Error sending message to parent\", message, e);\n }\n }\n}\n\nclass SbIframeEventInternal<T = Record<string, any>> extends Event {\n data: { payload: T; startTime: number; [key: string]: any };\n constructor(\n type: FromParentToChildMessageTypes,\n data: { payload: T; startTime: number; [key: string]: any },\n ) {\n super(type);\n this.data = data;\n }\n}\n\n// We are using a custom event target so that you each of our custom postMessage types\n// is a separate handler\ninterface MessageHandler extends EventTarget {\n addEventListener<MT extends FromParentToChildMessageTypes>(\n type: MT,\n callback: IframeEventHandler<MT>,\n ): void;\n addEventListener(\n type: string,\n callback: EventListenerOrEventListenerObject | null,\n ): void;\n removeEventListener<MT extends FromParentToChildMessageTypes>(\n type: MT,\n callback: IframeEventHandler<MT>,\n ): void;\n removeEventListener(\n type: string,\n callback: EventListenerOrEventListenerObject | null,\n ): void;\n}\n\n// This is a hack to get around the fact that we can't overload the addEventListener method\nclass SbMessageHandler extends (EventTarget as {\n new (): MessageHandler;\n prototype: MessageHandler;\n}) {\n // Parent implements all functionalityza\n}\n\nexport type IframeEventHandler<MT extends FromParentToChildMessageTypes> = (\n event: SbIframeEventInternal<FromParentToChildMessageTypesMap[MT]>,\n) => void;\n\nexport const iframeMessageHandler = new SbMessageHandler();\n","import type { PropertiesPanelDefinition } from \"@superblocksteam/library-shared/props\";\nimport type {\n AiContextMode,\n ApiRunRecord,\n ConsoleLogEntry,\n EditOperationPayload,\n EditOperationType,\n InteractionMode,\n RuntimeErrorData,\n SbElement,\n SbSelector,\n} from \"@superblocksteam/library-shared/types\";\nimport type { Profile } from \"@superblocksteam/shared\";\n\nimport type { FromChildToParentMessageTypesMap } from \"../lib/index.js\";\nimport { sendMessageImmediately } from \"../lib/internal-details/lib/iframe.js\";\nimport type {\n LoadErrorSource,\n StreamEvent,\n RouteInfo,\n ScreenshotReadyReason,\n} from \"../lib/internal-details/lib/types.js\";\n\n// interface for the public methods in SuperblocksEditorBridge\nexport interface SuperblocksParentBridgeInterface {\n // Connection methods\n connected(): void;\n sendReady(connectionStartTime?: number): void;\n sendLoadError(error: string, source?: LoadErrorSource): void;\n sendClearLoadError(): void;\n sendAppFrameWillReload(): void;\n\n // Notification methods\n sendNotification(\n type: \"success\" | \"error\" | \"info\" | \"warning\",\n message: string,\n description?: string,\n ): void;\n\n // Widget Operations\n selectWidgets(sourceIds: SbElement[], selectorIdHint?: SbSelector): void;\n editOpRequest<T extends EditOperationType>(\n type: T,\n payload: EditOperationPayload<T>[\"payload\"],\n ): void;\n undo(): void;\n redo(): void;\n\n // API Operations\n sendStreamedApiEvent(event: StreamEvent, apiName: string): void;\n sendStreamedApiMessage(message: any, apiName: string): void;\n setApiStarted(apiName: string): void;\n setApiResponse(apiName: string, response: unknown): void;\n\n // Navigation Operations\n navigateTo(path: string, newWindow?: boolean): void;\n\n // Properties Panel Operations\n updatePropertiesPanels(\n updates: Record<string, PropertiesPanelDefinition>,\n ): void;\n addPropertiesPanel(id: string, definition: PropertiesPanelDefinition): void;\n addApiRunRecord(apiId: string, run: ApiRunRecord): void;\n updateApiRunRecord(\n apiId: string,\n callId: string,\n updates: Partial<Omit<ApiRunRecord, \"id\" | \"callId\">>,\n ): void;\n\n // Editor Synced Store Operations\n initializeEditorSyncedStore(\n payload: FromChildToParentMessageTypesMap[\"codeMode/editor-synced-store/init\"],\n ): void;\n updateEditorSyncedStore(\n payload: FromChildToParentMessageTypesMap[\"codeMode/editor-synced-store/update\"],\n ): void;\n\n // Promise Operations\n resolvePromise(callbackId: string, payload: unknown): void;\n rejectPromise(callbackId: string, payload: unknown): void;\n\n // Click Operations\n canvasClicked(): void;\n registerContextMenuClick(\n sourceId: SbElement,\n selectorId: SbSelector,\n clientX: number,\n clientY: number,\n ): void;\n\n // Route Operations\n updateRoute(routeInfo: RouteInfo): void;\n\n // Socket Operations\n socketError(message: string, connectionStartTime?: number): void;\n\n // AI Operations\n aiGenerate(prompt: string, forceSend?: boolean): void;\n addComponentToAiContext(sourceId: SbElement, selectorId: SbSelector): void;\n toggleComponentInAiContext(\n sourceId: SbElement,\n selectorId: SbSelector,\n label?: string,\n ): void;\n setAiContextMode(mode: AiContextMode): void;\n sendAiLoaderState?(shouldShowLoader: boolean): void;\n sendRuntimeError(data: RuntimeErrorData, forceSend?: boolean): void;\n sendClearRuntimeError(id: string, forceSend?: boolean): void;\n sendConsoleLog(data: ConsoleLogEntry, forceSend?: boolean): void;\n\n setInteractionMode(mode: InteractionMode): void;\n\n // Keyboard Operations\n forwardKeypress(\n keys: string,\n eventInfo: {\n code: string;\n key: string;\n altKey: boolean;\n ctrlKey: boolean;\n shiftKey: boolean;\n },\n ): void;\n\n // Screenshot Operations\n sendCaptureScreenshotResponse(\n callbackId: string,\n dataUrl?: string,\n error?: string,\n ): void;\n sendPingAppReadyForScreenshotResponse(\n callbackId: string,\n isReady: boolean,\n reason?: ScreenshotReadyReason,\n ): void;\n\n // Profile Operations\n updateProfiles(profiles: {\n available: Profile[];\n selected: Profile;\n default: Profile;\n }): void;\n}\n\nexport class DeployedParentBridge implements SuperblocksParentBridgeInterface {\n navigateTo(url: string, newWindow?: boolean): void {\n sendMessageImmediately({\n type: \"navigate-to\",\n payload: {\n url,\n newWindow,\n },\n });\n }\n\n connected(): void {}\n sendReady(_connectionStartTime?: number): void {}\n sendLoadError(_error: string, _source?: LoadErrorSource): void {}\n sendClearLoadError(): void {}\n sendAppFrameWillReload(): void {}\n sendNotification(\n _type: \"success\" | \"error\" | \"info\" | \"warning\",\n _message: string,\n _description?: string,\n ): void {}\n selectWidgets(_sourceIds: SbElement[], _selectorIdHint?: SbSelector): void {}\n editOpRequest<T extends EditOperationType>(\n _type: T,\n _payload: EditOperationPayload<T>[\"payload\"],\n ): void {}\n undo(): void {}\n redo(): void {}\n sendStreamedApiEvent(_event: StreamEvent, _apiName: string): void {}\n sendStreamedApiMessage(_message: any, _apiName: string): void {}\n setApiStarted(_apiName: string): void {}\n setApiResponse(_apiName: string, _response: unknown): void {}\n updatePropertiesPanels(\n _updates: Record<string, PropertiesPanelDefinition>,\n ): void {}\n addPropertiesPanel(\n _id: string,\n _definition: PropertiesPanelDefinition,\n ): void {}\n addApiRunRecord(_apiId: string, _run: ApiRunRecord): void {}\n updateApiRunRecord(\n _apiId: string,\n _callId: string,\n _updates: Partial<Omit<ApiRunRecord, \"id\" | \"callId\">>,\n ): void {}\n initializeEditorSyncedStore(\n _payload: FromChildToParentMessageTypesMap[\"codeMode/editor-synced-store/init\"],\n ): void {}\n updateEditorSyncedStore(\n _payload: FromChildToParentMessageTypesMap[\"codeMode/editor-synced-store/update\"],\n ): void {}\n resolvePromise(_callbackId: string, _payload: unknown): void {}\n rejectPromise(_callbackId: string, _payload: unknown): void {}\n canvasClicked(): void {}\n registerContextMenuClick(\n _sourceId: SbElement,\n _selectorId: SbSelector,\n _clientX: number,\n _clientY: number,\n ): void {}\n updateRoute(routeInfo: RouteInfo): void {\n sendMessageImmediately({\n type: \"route-change\",\n payload: routeInfo,\n });\n }\n socketError(_message: string, _connectionStartTime?: number): void {}\n aiGenerate(_prompt: string): void {}\n addComponentToAiContext(\n _sourceId: SbElement,\n _selectorId: SbSelector,\n ): void {}\n toggleComponentInAiContext(\n _sourceId: SbElement,\n _selectorId: SbSelector,\n _label?: string,\n ): void {}\n setAiContextMode(_mode: AiContextMode): void {}\n sendAiLoaderState(_shouldShowLoader: boolean): void {}\n sendRuntimeError(_data: RuntimeErrorData): void {}\n sendClearRuntimeError(_id: string): void {}\n sendConsoleLog(_data: ConsoleLogEntry, _forceSend?: boolean): void {}\n setInteractionMode(_mode: InteractionMode): void {}\n forwardKeypress(\n _keys: string,\n _eventInfo: {\n code: string;\n key: string;\n altKey: boolean;\n ctrlKey: boolean;\n shiftKey: boolean;\n },\n ): void {}\n\n sendCaptureScreenshotResponse(\n _callbackId: string,\n _dataUrl?: string,\n _error?: string,\n ): void {}\n sendPingAppReadyForScreenshotResponse(\n _callbackId: string,\n _isReady: boolean,\n _reason?: ScreenshotReadyReason,\n ): void {}\n updateProfiles(profiles: {\n available: Profile[];\n selected: Profile;\n default: Profile;\n }): void {\n // Send profile update to parent window (for preview and deployed modes)\n // This allows the parent Redux store to be updated with the new profile selection\n sendMessageImmediately({\n type: \"iframe-action-batch\",\n payload: [\n {\n type: \"UPDATE_PROFILES\",\n payload: profiles,\n },\n ],\n });\n }\n}\n","import { throttle } from \"lodash\";\n\nimport type { PayloadAction } from \"@superblocksteam/library-shared/types\";\n\nimport { sendMessageImmediately } from \"../lib/internal-details/lib/iframe.js\";\n\nconst MESSAGE_BATCH_TIME = 50;\n\nconst DEFAULT_KEY = \"default\";\n\nexport type QueueMergeOptions = {\n key: string;\n mergeFn: (\n existing: PayloadAction<unknown>[] | undefined,\n newMessage: PayloadAction<unknown>,\n ) => PayloadAction<unknown>[]; // mutations allowed\n};\n\nclass MessageQueue {\n private keyedActionQueue: Record<string, PayloadAction<unknown>[]> = {};\n\n constructor() {}\n\n private flattenKeyedQueue(): PayloadAction<unknown>[] {\n return Object.values(this.keyedActionQueue).flat();\n }\n\n private triggerSendFromQueue = throttle(() => {\n sendMessageImmediately(\n {\n type: \"iframe-action-batch\",\n payload: this.flattenKeyedQueue(),\n },\n {\n overrideStartTime: Date.now() - MESSAGE_BATCH_TIME,\n },\n );\n this.keyedActionQueue = {};\n }, MESSAGE_BATCH_TIME);\n\n public queueMessage(\n message: PayloadAction<unknown>,\n mergeOptions?: QueueMergeOptions,\n ) {\n if (mergeOptions) {\n const { key, mergeFn } = mergeOptions;\n this.keyedActionQueue[key] ??= [];\n this.keyedActionQueue[key] = mergeFn(this.keyedActionQueue[key], message);\n } else {\n this.keyedActionQueue[DEFAULT_KEY] ??= [];\n this.keyedActionQueue[DEFAULT_KEY].push(message);\n }\n\n this.triggerSendFromQueue();\n }\n}\n\nexport default new MessageQueue();\n","import type { PropertiesPanelDefinition } from \"@superblocksteam/library-shared/props\";\nimport type {\n AiContextMode,\n EditOperationPayload,\n EditOperationType,\n PayloadAction,\n InteractionMode,\n RuntimeErrorData,\n SbElement,\n SbSelector,\n ConsoleLogEntry,\n} from \"@superblocksteam/library-shared/types\";\nimport type { Profile } from \"@superblocksteam/shared\";\n\nimport type {\n FromChildToParentMessageTypes,\n FromChildToParentMessageTypesMap,\n} from \"../lib/index.js\";\nimport { isEditMode } from \"../lib/internal-details/is-edit-mode.js\";\nimport { sendMessageImmediately as legacySendImmediate } from \"../lib/internal-details/lib/iframe.js\";\nimport type {\n LoadErrorSource,\n StreamEvent,\n RouteInfo,\n ScreenshotReadyReason,\n} from \"../lib/internal-details/lib/types.js\";\nimport {\n DeployedParentBridge,\n type SuperblocksParentBridgeInterface,\n} from \"./base-editor-bridge.js\";\nimport { getEditStore } from \"./get-edit-store.js\";\nimport {\n type QueueMergeOptions,\n default as MessageQueue,\n} from \"./message-queue.js\";\n\ntype MessagePayload<T extends FromChildToParentMessageTypes> = {\n type: T;\n payload: FromChildToParentMessageTypesMap[T];\n callbackId?: string;\n};\n\nexport class SuperblocksEditorBridge implements SuperblocksParentBridgeInterface {\n private static instance: SuperblocksParentBridgeInterface;\n\n private messagesToSend: Array<{\n payload: MessagePayload<any>;\n mergeOptions?: QueueMergeOptions;\n }> = [];\n private connectedToParent = false;\n\n public static getInstance(): SuperblocksParentBridgeInterface {\n const editMode = isEditMode();\n if (!SuperblocksEditorBridge.instance) {\n SuperblocksEditorBridge.instance = editMode\n ? new SuperblocksEditorBridge()\n : new DeployedParentBridge();\n }\n return SuperblocksEditorBridge.instance;\n }\n\n public connected() {\n this.connectedToParent = true;\n this.messagesToSend.forEach((message) =>\n this.queueMessage(message.payload, message.mergeOptions),\n );\n this.messagesToSend = [];\n }\n\n public sendReady(connectionStartTime?: number) {\n this.sendImmediate<\"sb-ready\">(\n {\n type: \"sb-ready\",\n payload: { connectionStartTime },\n },\n true,\n );\n }\n\n public sendLoadError(error: string, source?: LoadErrorSource) {\n this.sendImmediate<\"sb-load-error\">(\n {\n type: \"sb-load-error\",\n payload: { error, ...(source ? { source } : {}) },\n },\n true,\n );\n }\n\n public sendClearLoadError() {\n this.sendImmediate<\"sb-clear-load-error\">(\n {\n type: \"sb-clear-load-error\",\n payload: void 0,\n },\n true,\n );\n }\n\n public sendAppFrameWillReload() {\n this.sendImmediate<\"sb-app-frame-will-reload\">(\n {\n type: \"sb-app-frame-will-reload\",\n payload: void 0,\n },\n true,\n );\n }\n\n // Notifications\n public sendNotification(\n type: \"success\" | \"error\" | \"info\" | \"warning\",\n message: string,\n description?: string,\n ) {\n this.queueMessage<\"codeMode/sendNotification\">({\n type: \"codeMode/sendNotification\",\n payload: { type, message, description },\n });\n }\n\n // Widget Operations\n public selectWidgets(sourceIds: SbElement[], selectorIdHint?: SbSelector) {\n this.queueMessage<\"client:selectWidgets\">({\n type: \"client:selectWidgets\",\n payload: { sourceIds, selectorIdHint },\n });\n }\n\n public editOpRequest<T extends EditOperationType>(\n type: T,\n payload: EditOperationPayload<T>[\"payload\"],\n ) {\n this.sendImmediate<\"sb-edit-operation-request\">({\n type: \"sb-edit-operation-request\",\n payload: { type, payload },\n });\n }\n\n public undo() {\n this.sendImmediate<\"undo\">({\n type: \"undo\",\n payload: void 0,\n });\n }\n\n public redo() {\n this.sendImmediate<\"redo\">({\n type: \"redo\",\n payload: void 0,\n });\n }\n\n public sendStreamedApiEvent(event: StreamEvent, apiName: string) {\n this.sendImmediate<\"api/stream-event\">({\n type: \"api/stream-event\",\n payload: { event, apiName },\n });\n }\n\n public sendStreamedApiMessage(message: any, apiName: string) {\n this.sendImmediate<\"api/stream-message\">({\n type: \"api/stream-message\",\n payload: { message, apiName },\n });\n }\n\n public setApiStarted(apiName: string) {\n this.sendImmediate<\"api/started-execution\">({\n type: \"api/started-execution\",\n payload: { apiName },\n });\n }\n\n public setApiResponse(apiName: string, response: unknown) {\n this.sendImmediate<\"api/set-api-response\">({\n type: \"api/set-api-response\",\n payload: { apiName, response },\n });\n }\n\n // Navigation Operations\n public navigateTo(path: string, newWindow?: boolean) {\n this.sendImmediate<\"navigate-to\">({\n type: \"navigate-to\",\n payload: { url: path, newWindow },\n });\n }\n\n // Properties Panel Operations\n public updatePropertiesPanels(\n updates: Record<string, PropertiesPanelDefinition>,\n ) {\n this.queueMessage<\"codeMode/updatePropertiesPanels\">({\n type: \"codeMode/updatePropertiesPanels\",\n payload: updates,\n });\n }\n\n public addPropertiesPanel(id: string, definition: PropertiesPanelDefinition) {\n this.queueMessage<\"codeMode/addPropertiesPanel\">({\n type: \"codeMode/addPropertiesPanel\",\n payload: { id, definition },\n });\n }\n\n public addApiRunRecord(\n apiId: string,\n run: FromChildToParentMessageTypesMap[\"codeMode/addApiRunRecord\"][\"run\"],\n ) {\n this.queueMessage<\"codeMode/addApiRunRecord\">({\n type: \"codeMode/addApiRunRecord\",\n payload: { apiId, run },\n });\n }\n\n public updateApiRunRecord(\n apiId: string,\n callId: string,\n updates: Partial<\n Omit<\n FromChildToParentMessageTypesMap[\"codeMode/addApiRunRecord\"][\"run\"],\n \"id\" | \"callId\"\n >\n >,\n ) {\n this.queueMessage<\"codeMode/updateApiRunRecord\">({\n type: \"codeMode/updateApiRunRecord\",\n payload: { apiId, callId, updates },\n });\n }\n\n // Editor Synced Store Operations\n public initializeEditorSyncedStore(\n payload: FromChildToParentMessageTypesMap[\"codeMode/editor-synced-store/init\"],\n ) {\n this.queueMessage<\"codeMode/editor-synced-store/init\">({\n type: \"codeMode/editor-synced-store/init\",\n payload,\n });\n }\n\n private mergeSyncedStoreUpdate(\n existingActions: PayloadAction<unknown>[] | undefined,\n newAction: PayloadAction<unknown>,\n ) {\n if (!existingActions || existingActions.length === 0) {\n return [newAction];\n }\n const firstAction = existingActions[0] as PayloadAction<\n FromChildToParentMessageTypesMap[\"codeMode/editor-synced-store/update\"]\n >;\n const newActionPatches = (\n newAction as PayloadAction<\n FromChildToParentMessageTypesMap[\"codeMode/editor-synced-store/update\"]\n >\n ).payload.patch;\n firstAction.payload.patch = Array.isArray(firstAction.payload.patch)\n ? firstAction.payload.patch\n : [firstAction.payload.patch];\n firstAction.payload.patch.push(\n ...(Array.isArray(newActionPatches)\n ? newActionPatches\n : [newActionPatches]),\n );\n\n return existingActions;\n }\n\n public updateEditorSyncedStore(\n payload: FromChildToParentMessageTypesMap[\"codeMode/editor-synced-store/update\"],\n ) {\n this.queueMessage<\"codeMode/editor-synced-store/update\">(\n {\n type: \"codeMode/editor-synced-store/update\",\n payload,\n },\n {\n key: `synced-store-update-${payload.storeId}`,\n mergeFn: this.mergeSyncedStoreUpdate,\n },\n );\n }\n\n // Promise Operations\n public resolvePromise(callbackId: string, payload: unknown) {\n this.sendImmediate<\"resolve-promise\">({\n type: \"resolve-promise\",\n callbackId,\n payload,\n });\n }\n\n public rejectPromise(callbackId: string, payload: unknown) {\n this.sendImmediate<\"reject-promise\">({\n type: \"reject-promise\",\n callbackId,\n payload,\n });\n }\n\n public canvasClicked() {\n this.sendImmediate<\"register-click\">({\n type: \"register-click\",\n payload: {\n type: \"INSIDE_IFRAME_CLICKED\",\n context: {\n sourceId: \"\",\n clientX: 0,\n clientY: 0,\n },\n },\n });\n }\n\n public registerContextMenuClick(\n sourceId: SbElement,\n selectorId: SbSelector,\n clientX: number,\n clientY: number,\n ) {\n this.sendImmediate<\"register-click\">({\n type: \"register-click\",\n payload: {\n type: \"OPEN_CONTEXT_MENU\",\n context: {\n sourceId,\n selectorId,\n clientX,\n clientY,\n },\n },\n });\n }\n\n public updateRoute(routeInfo: RouteInfo) {\n this.sendImmediate(\n {\n type: \"route-change\",\n payload: routeInfo,\n },\n // a route change might cause this.connectedToParent to be false,\n // make sure the message is always sent\n true,\n );\n }\n\n public addComponentToAiContext(sourceId: SbElement, selectorId: SbSelector) {\n const editStore = getEditStore();\n\n if (editStore?.ai.isAlternateSourceIdTarget(sourceId, selectorId)) {\n editStore.ai.addTargetedSelector(selectorId);\n return;\n }\n\n const label =\n editStore.runtimeTrackingStore.getComponent(selectorId)?.displayName;\n\n this.sendImmediate<\"ai-updates\">({\n type: \"ai-updates\",\n payload: {\n type: \"add-component-to-context\",\n component: sourceId,\n label,\n selectorId,\n },\n });\n }\n\n public toggleComponentInAiContext(\n sourceId: SbElement,\n selectorId: SbSelector,\n label?: string,\n ) {\n const editStore = getEditStore();\n\n if (editStore?.ai.isAlternateSourceIdTarget(sourceId, selectorId)) {\n editStore.ai.toggleTargetedSelector(selectorId);\n return;\n }\n this.sendImmediate<\"ai-updates\">({\n type: \"ai-updates\",\n payload: {\n type: \"toggle-component-in-context\",\n component: sourceId,\n label: label,\n selectorId,\n },\n });\n }\n\n public setAiContextMode(mode: AiContextMode) {\n this.sendImmediate<\"ai-updates\">({\n type: \"ai-updates\",\n payload: { type: \"set-ai-context-mode\", mode },\n });\n }\n\n public aiGenerate(prompt: string, forceSend = false) {\n const sanitizedPrompt = clampPromptLength(prompt);\n this.sendImmediate<\"ai-updates\">(\n {\n type: \"ai-updates\",\n payload: {\n type: \"ai-generate\",\n prompt: sanitizedPrompt,\n },\n },\n forceSend,\n );\n }\n\n public sendAiLoaderState(shouldShowLoader: boolean) {\n this.sendImmediate<\"ai-updates\">({\n type: \"ai-updates\",\n payload: { type: \"loader-state\", shouldShowLoader },\n });\n }\n\n public socketError(message: string, connectionStartTime?: number) {\n this.sendImmediate<\"socket/error\">({\n type: \"socket/error\",\n payload: { message, connectionStartTime },\n });\n }\n\n public sendRuntimeError(data: RuntimeErrorData, forceSend = false) {\n this.sendImmediate<\"runtime-error\">(\n {\n type: \"runtime-error\",\n payload: data,\n },\n forceSend,\n );\n }\n\n public sendClearRuntimeError(id: string, forceSend = false) {\n this.sendImmediate<\"clear-runtime-error\">(\n {\n type: \"clear-runtime-error\",\n payload: { id },\n },\n forceSend,\n );\n }\n\n public sendConsoleLog(data: ConsoleLogEntry, forceSend = false) {\n this.sendImmediate<\"console-log\">(\n {\n type: \"console-log\",\n payload: data,\n },\n forceSend,\n );\n }\n\n public setInteractionMode(mode: InteractionMode) {\n this.sendImmediate<\"set-interaction-mode\">({\n type: \"set-interaction-mode\",\n payload: { interactionMode: mode },\n });\n }\n\n // Keyboard Operations\n public forwardKeypress(\n keys: string,\n eventInfo: {\n code: string;\n key: string;\n altKey: boolean;\n ctrlKey: boolean;\n shiftKey: boolean;\n },\n ) {\n this.sendImmediate<\"keypress\">({\n type: \"keypress\",\n payload: { keys, eventInfo },\n });\n }\n\n // Screenshot Operations\n public sendCaptureScreenshotResponse(\n callbackId: string,\n dataUrl?: string,\n error?: string,\n ) {\n this.sendImmediate<\"capture-screenshot-response\">({\n type: \"capture-screenshot-response\",\n payload: {\n callbackId,\n dataUrl,\n error,\n },\n });\n }\n\n public sendPingAppReadyForScreenshotResponse(\n callbackId: string,\n isReady: boolean,\n reason?: ScreenshotReadyReason,\n ) {\n this.sendImmediate<\"ping-app-ready-for-screenshot-response\">({\n type: \"ping-app-ready-for-screenshot-response\",\n payload: {\n callbackId,\n isReady,\n reason,\n },\n });\n }\n\n // Profile Operations\n public updateProfiles(profiles: {\n available: Profile[];\n selected: Profile;\n default: Profile;\n }) {\n this.sendImmediate<\"iframe-action-batch\">({\n type: \"iframe-action-batch\",\n payload: [\n {\n type: \"UPDATE_PROFILES\",\n payload: profiles,\n },\n ],\n });\n }\n\n // Private implementation details\n private queueMessage<T extends FromChildToParentMessageTypes>(\n message: MessagePayload<T>,\n mergeOptions?: QueueMergeOptions,\n ) {\n if (!this.connectedToParent) {\n this.messagesToSend.push({ payload: message, mergeOptions });\n } else {\n MessageQueue.queueMessage(message, mergeOptions);\n }\n }\n\n private sendImmediate<T extends FromChildToParentMessageTypes>(\n message: MessagePayload<T>,\n forceSend = false,\n ) {\n if (!this.connectedToParent && !forceSend) {\n this.messagesToSend.push({ payload: message });\n } else {\n legacySendImmediate(message);\n }\n }\n}\n\n// Roughly 4:1 chars to tokens, so 4k tokens\nconst MAX_AI_PROMPT_LENGTH = 16000;\nconst TRUNCATION_SUFFIX = \"... (truncated)\";\n\nfunction clampPromptLength(prompt: string): string {\n if (prompt.length <= MAX_AI_PROMPT_LENGTH) {\n return prompt;\n }\n\n const available = Math.max(\n MAX_AI_PROMPT_LENGTH - TRUNCATION_SUFFIX.length,\n 0,\n );\n return `${prompt.slice(0, available)}${TRUNCATION_SUFFIX}`;\n}\n\nexport const editorBridge = SuperblocksEditorBridge.getInstance();\n","import { action } from \"mobx\";\nimport {\n matchRoutes,\n type DataRouter,\n type Location,\n type Params,\n} from \"react-router\";\n\nimport { getQueryParams } from \"@superblocksteam/library-shared\";\n\nimport { editorBridge } from \"../../edit-mode/superblocks-editor-bridge.js\";\nimport type { RootStore } from \"./lib/root-store.js\";\nimport type { RouteInfo } from \"./lib/types.js\";\n\nexport class LocationStore {\n route?: RouteInfo;\n rootStore: RootStore;\n\n constructor(rootStore: RootStore) {\n this.rootStore = rootStore;\n }\n\n @action\n updateLocation(\n location: Location,\n routes: DataRouter[\"routes\"],\n params: Readonly<Params<string>>,\n ): void {\n this.route = this.locationToRouteInfo(location, routes, params);\n this.sendLocationToEditor();\n }\n\n sendLocationToEditor() {\n if (!this.route) return;\n editorBridge.updateRoute(this.route);\n }\n\n private matchesToRoutePattern(matches: ReturnType<typeof matchRoutes>) {\n if (!matches || matches.length === 0) return undefined;\n\n const segments: string[] = [];\n for (const match of matches) {\n const path = match.route?.path;\n if (!path) continue;\n // Skip wildcard-only segments here; if present, include \"*\" as a segment\n const normalized = path === \"*\" ? \"*\" : path.replace(/^\\/+/, \"\");\n if (!normalized) continue;\n segments.push(normalized);\n }\n\n if (segments.length === 0) {\n const last = matches.at(-1);\n const fallback = last?.pathname;\n return typeof fallback === \"string\" ? fallback : undefined;\n }\n\n const joined = \"/\" + segments.join(\"/\");\n return joined.replace(/\\/{2,}/g, \"/\");\n }\n\n locationToRouteInfo(\n location: Location,\n routes: DataRouter[\"routes\"],\n params: Readonly<Params<string>>,\n ): RouteInfo | undefined {\n const matches = matchRoutes(routes, location.pathname);\n const match = matches?.at(-1);\n\n if (!match?.pathname) return;\n const routePattern = this.matchesToRoutePattern(matches) ?? match.pathname;\n\n return {\n hash: location.hash,\n pathname: location.pathname,\n queryParams: getQueryParams(location.search),\n route: routePattern,\n routeParams: params,\n };\n }\n}\n","<svg width=\"16\" height=\"16\" viewBox=\"0 0 16 16\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\">\n<path fill-rule=\"evenodd\" clip-rule=\"evenodd\" d=\"M8 15C11.866 15 15 11.866 15 8C15 4.13401 11.866 1 8 1C4.13401 1 1 4.13401 1 8C1 11.866 4.13401 15 8 15ZM8.75001 5C8.75001 4.58579 8.41422 4.25 8.00001 4.25C7.58579 4.25 7.25001 4.58579 7.25001 5V8C7.25001 8.41421 7.58579 8.75 8.00001 8.75C8.41422 8.75 8.75001 8.41421 8.75001 8V5ZM8 9.75001C7.44772 9.75001 7 10.1977 7 10.75C7 11.3023 7.44772 11.75 8 11.75C8.55228 11.75 9 11.3023 9 10.75C9 10.1977 8.55228 9.75001 8 9.75001Z\" fill=\"currentColor\"/>\n</svg>\n","<svg width=\"16\" height=\"16\" viewBox=\"0 0 16 16\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\">\n<path fill-rule=\"evenodd\" clip-rule=\"evenodd\" d=\"M15 8C15 11.866 11.866 15 8 15C4.13401 15 1 11.866 1 8C1 4.13401 4.13401 1 8 1C11.866 1 15 4.13401 15 8ZM5.94194 5.05806C5.69786 4.81398 5.30214 4.81398 5.05806 5.05806C4.81398 5.30214 4.81398 5.69786 5.05806 5.94194L7.11612 8L5.05806 10.0581C4.81398 10.3021 4.81398 10.6979 5.05806 10.9419C5.30214 11.186 5.69786 11.186 5.94194 10.9419L8 8.88388L10.0581 10.9419C10.3021 11.186 10.6979 11.186 10.9419 10.9419C11.186 10.6979 11.186 10.3021 10.9419 10.0581L8.88388 8L10.9419 5.94194C11.186 5.69786 11.186 5.30214 10.9419 5.05806C10.6979 4.81398 10.3021 4.81398 10.0581 5.05806L8 7.11612L5.94194 5.05806Z\" fill=\"currentColor\"/>\n</svg>\n","<svg width=\"16\" height=\"16\" viewBox=\"0 0 16 16\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\">\n<path d=\"M8 1C6.61553 1 5.26216 1.41054 4.11101 2.17971C2.95987 2.94888 2.06266 4.04213 1.53285 5.32122C1.00303 6.6003 0.86441 8.00776 1.13451 9.36563C1.4046 10.7235 2.07129 11.9708 3.05026 12.9497C4.02922 13.9287 5.2765 14.5954 6.63437 14.8655C7.99224 15.1356 9.3997 14.997 10.6788 14.4672C11.9579 13.9373 13.0511 13.0401 13.8203 11.889C14.5895 10.7378 15 9.38447 15 8C14.9964 6.14458 14.2578 4.36617 12.9458 3.05418C11.6338 1.7422 9.85542 1.00356 8 1ZM7.86539 4.23077C8.02513 4.23077 8.18129 4.27814 8.31412 4.36689C8.44694 4.45564 8.55046 4.58178 8.6116 4.72937C8.67273 4.87696 8.68872 5.03936 8.65756 5.19603C8.62639 5.35271 8.54947 5.49663 8.43651 5.60959C8.32355 5.72254 8.17964 5.79947 8.02296 5.83063C7.86628 5.8618 7.70388 5.8458 7.5563 5.78467C7.40871 5.72354 7.28257 5.62001 7.19381 5.48719C7.10506 5.35437 7.05769 5.19821 7.05769 5.03846C7.05769 4.82425 7.14279 4.61881 7.29426 4.46734C7.44573 4.31586 7.65117 4.23077 7.86539 4.23077ZM8.53846 11.7692H8C7.85719 11.7692 7.72023 11.7125 7.61925 11.6115C7.51827 11.5105 7.46154 11.3736 7.46154 11.2308V8C7.31873 8 7.18177 7.94327 7.08079 7.84229C6.97981 7.74131 6.92308 7.60435 6.92308 7.46154C6.92308 7.31873 6.97981 7.18177 7.08079 7.08079C7.18177 6.97981 7.31873 6.92308 7.46154 6.92308H8C8.14281 6.92308 8.27977 6.97981 8.38075 7.08079C8.48173 7.18177 8.53846 7.31873 8.53846 7.46154V10.6923C8.68127 10.6923 8.81823 10.749 8.91921 10.85C9.0202 10.951 9.07692 11.088 9.07692 11.2308C9.07692 11.3736 9.0202 11.5105 8.91921 11.6115C8.81823 11.7125 8.68127 11.7692 8.53846 11.7692Z\" fill=\"currentColor\"/>\n</svg>\n","<svg width=\"16\" height=\"16\" viewBox=\"0 0 16 16\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\">\n<path fill-rule=\"evenodd\" clip-rule=\"evenodd\" d=\"M8 15C11.866 15 15 11.866 15 8C15 4.13401 11.866 1 8 1C4.13401 1 1 4.13401 1 8C1 11.866 4.13401 15 8 15ZM11.4419 6.94194C11.686 6.69786 11.686 6.30214 11.4419 6.05806C11.1979 5.81398 10.8021 5.81398 10.5581 6.05806L7.5 9.11612L5.94194 7.55806C5.69786 7.31398 5.30214 7.31398 5.05806 7.55806C4.81398 7.80214 4.81398 8.19786 5.05806 8.44194L7.05806 10.4419C7.30214 10.686 7.69786 10.686 7.94194 10.4419L11.4419 6.94194Z\" fill=\"currentColor\"/>\n</svg>\n","export const colors = {\n WHITE: \"#FFFFFF\",\n BLACK: \"#000000\",\n PLATFORM_BLACK: \"#0E141B\",\n\n // TODO: Consider replace WHITE with this.\n OFF_WHITE: \"#F2F2F2\",\n DISABLED: \"rgba(0, 0, 0, 0.25)\",\n\n GREY_25: \"#F9FAFB\",\n GREY_50: \"#F3F4F6\",\n GREY_100: \"#E8EAED\",\n GREY_200: \"#C6CAD2\",\n GREY_300: \"#A4AAB7\",\n GREY_400: \"#818A9C\",\n GREY_500: \"#6C7689\",\n GREY_600: \"#5A6272\",\n GREY_700: \"#454D5F\",\n GREY_800: \"#2F3437\",\n GREY_900: \"#121517\",\n GRAY_GRID: \"#CCD3DB\",\n\n RED_500_8: \"rgba(255, 72, 72, 0.08)\",\n RED_25: \"#FF48481F\",\n RED_500: \"#FF4848\",\n RED_600: \"#DB4949\",\n RED_700: \"#C54141\",\n\n ORANGE_25: \"#FFEEC5\",\n ORANGE_600: \"#FA8A0F\",\n\n SUBTLE_BLUE: \"#29bbff14\", // Deprecated. Not defined in figma\n SUBTLE_BLUE_SOLID: \"#eefaff\", // Deprecated. Not defined in figma\n\n ACCENT_BLUE_NEW_DARKER: \"#0087E0\",\n BLUE_MINMAX_LABELS: \"#0062A3\",\n DRAG_PREVIEW_BLUE: \"rgba(0, 135, 224, 0.16)\",\n ACCENT_BLUE_500: \"#27BBFF\",\n ACCENT_BLUE_500_04: \"#27BBFF0A\",\n ACCENT_BLUE_500_25: \"#27BBFF14\",\n ACCENT_BLUE_500_50: \"#27BBFF1F\",\n ACCENT_BLUE_500_18: \"#27BBFF2E\", // Deprecated. Not defined in figma\n ACCENT_BLUE_500_24: \"#27BBFF3D\", // Deprecated. Not defined in figma\n ACCENT_BLUE_500_48: \"#27BBFF7A\", // Deprecated. Not defined in figma\n ACCENT_BLUE_600: \"#00A8F5\",\n ACCENT_BLUE_700: \"#009AE0\",\n ACCENT_ORANGE: \"#FF9F35\",\n ACCENT_ORANGE_04: \"#FF9F350A\",\n ACCENT_ORANGE_24: \"#FF9F353D\",\n LIGHT_ORANGE: \"#FF9F351E\",\n ACCENT_ORANGE_600: \"#FA8A0F\",\n SUBTLE_PURPLE: \"#643ADF14\",\n ACCENT_PURPLE: \"#643ADF\",\n LIGHT_PURPLE: \"#643ADF1E\",\n ACCENT_PURPLE_500: \"#7C4FF8\",\n ACCENT_PURPLE_600: \"#5227CE\",\n SUBTLE_GREEN: \"#14CDB714\",\n LIGHT_GREEN: \"#9BDCAD\",\n ACCENT_GREEN: \"#14CDB7\",\n ACCENT_GREEN_600: \"#08BAA5\",\n LIGHT_PINK: `rgba(255, 98, 164, 0.12)`,\n ACCENT_PINK: \"#FF62A4\",\n\n HOVER_BLUE: \"#E3F8FF\",\n HOVER_GREEN: \"#14CDB724\",\n\n CLICK_GREEN: \"#14CDB734\",\n\n INFO: \"#27BBFF\",\n WARNING: \"#FF9F35\",\n DANGER: \"#F45252\",\n DANGER_BRIGHT: \"rgba(255, 72, 72, 1.0)\",\n DANGER_SUBTLE: \"#F452521F\",\n SUCCESS: \"#0CC26D\",\n\n NONE: \"transparent\",\n} as const;\n","const MODIFIER_CLASSNAMES = {\n DISABLED_MODIFIER: \"sb-disabled\",\n ERROR_MODIFIER: \"sb-error\",\n ACTIVE_MODIFIER: \"sb-active\",\n};\n\nexport const CLASS_NAMES = {\n ...MODIFIER_CLASSNAMES,\n // user-controllable typefaces\n HEADING1: \"sb-heading-1\",\n HEADING2: \"sb-heading-2\",\n HEADING3: \"sb-heading-3\",\n HEADING4: \"sb-heading-4\",\n HEADING5: \"sb-heading-5\",\n HEADING6: \"sb-heading-6\",\n BODY1: \"sb-body-1\",\n BODY2: \"sb-body-2\",\n BODY3: \"sb-body-3\",\n LINK: \"sb-link\",\n INPUT_LABEL: \"sb-input-label\",\n LABEL: \"sb-label\",\n CODE_TEXT: \"sb-code\",\n INPUT_TEXT: \"sb-input-text\",\n INPUT_PLACEHOLDER: \"sb-input-placeholder\",\n BUTTON_LABEL: \"sb-button-label\",\n\n // built-in typefaces\n SYSTEM_TEXT: \"sb-system-text\",\n BUILTIN_BODY: \"sb-builtin-body\",\n ELLIPSIS_TEXT: \"sb-ellipsis-text\",\n\n // buttons\n BUTTON: \"sb-button\",\n PRIMARY_BUTTON: \"sb-button-primary\",\n SECONDARY_BUTTON: \"sb-button-secondary\",\n SECONDARY_NEUTRAL_BUTTON: \"sb-button-secondary-neutral\",\n TERTIARY_BUTTON: \"sb-button-tertiary\",\n SYSTEM_BUTTON: \"sb-button-system\",\n // inputs\n INPUT: \"sb-input\",\n SWITCH: \"sb-switch\",\n CHECKBOX: \"sb-checkbox\",\n RADIO: \"sb-radio\",\n // containers\n SECTION: \"sb-section\",\n ROUNDED_CONTAINER: \"sb-rounded-container\",\n\n CANVAS: \"sb-canvas\", // the inner canvas of a container\n DEFAULT_CONTAINER: \"sb-default-container\", // used for container-like wrappers (i.e. table, graph, etc.)\n\n DEFAULT_CONTAINER_STYLE_CARD: \"sb-default-container-style-card\", // used for container components\n DEFAULT_CONTAINER_STYLE_NONE: \"sb-default-container-style-none\", // used for container components\n\n DEFAULT_CONTAINER_BORDER: \"sb-default-container-border\", // used to render container borders, which are customizable + overlay the component\n\n CONTAINER_BORDER_OUTLINE: \"sb-container-border-overlay\",\n POPOVER_WRAPPER: \"sb-popover-wrapper\",\n TAB: \"sb-tab\",\n MODAL: \"sb-modal\",\n BORDER_BOTTOM: \"sb-util-border-bottom\",\n BORDER_TOP: \"sb-util-border-top\",\n NOTIFICATION: \"sb-notification\",\n STYLED_SCROLLBAR: \"sb-scrollable\",\n TOOLTIP: \"sb-tooltip\",\n // menus\n DROPDOWN: \"sb-dropdown\",\n DROPDOWN_MENU: \"sb-dropdown-menu\",\n MENU_ITEM: \"sb-menu-item\",\n TAG_INPUT: \"sb-tag-input\",\n DATEPICKER: \"sb-datepicker\",\n // icons\n DROPDOWN_CLEAR_ICON: \"sb-dropdown-clear-icon\",\n CARET_ICON: \"sb-caret-icon\",\n PRIMARY_COLOR_ICON: \"sb-primary-color-icon\",\n CLOSE_ICON: \"sb-close-icon\",\n ICON: \"sb-icon\",\n // misc\n PAGINATOR: \"sb-rc-paginator\",\n CODE_EDITOR: \"sb-code-editor\",\n ERROR_INLINE_MESSAGE: \"sb-error-inline-message\",\n};\n","import isString from \"lodash/isString\";\nimport React from \"react\";\nimport { toast } from \"sonner\";\nimport type { ToastT } from \"sonner\";\nimport styled from \"styled-components\";\n\nimport { NotificationPosition } from \"@superblocksteam/library-shared/types\";\nimport type { NotificationType } from \"@superblocksteam/library-shared/types\";\n\nimport WarningIcon from \"../assets/icons/system-danger.svg\";\nimport ErrorIcon from \"../assets/icons/system-error.svg\";\nimport InfoIcon from \"../assets/icons/system-info.svg\";\nimport SuccessIcon from \"../assets/icons/system-success.svg\";\nimport { colors } from \"../styling/colors.js\";\nimport { CLASS_NAMES } from \"../themes/classnames.js\";\n\ntype NotificationConfig = {\n key?: string;\n message: JSX.Element | string;\n description?: JSX.Element | string;\n // Duration in seconds\n duration?: number;\n placement?: NotificationPosition;\n style?: React.CSSProperties;\n dataTest?: string;\n type: NotificationType;\n};\n\n// Used to keep track of active notifications and collapse them when displayed\nconst activeNotifications = new Map<string, { count: number; message: any }>();\n\nconst StatusIconWrapper = styled.div<{\n color: string;\n}>`\n color: ${(props) => props.color};\n font-size: 16px;\n margin-top: -2px;\n margin-left: -10px;\n svg {\n width: 18px;\n height: 18px;\n }\n`;\n\nconst MessageWrapper = styled.div`\n font-size: 12px;\n font-weight: 500;\n line-height: 1.3;\n margin-left: -26px;\n margin-right: 0;\n white-space: pre-wrap;\n`;\n\nconst DescriptionWrapper = styled.div`\n font-size: 12px;\n margin-left: -26px;\n margin-right: -10px;\n`;\nconst styleMessage = (\n message: string | JSX.Element,\n dataTest?: string,\n): JSX.Element => {\n return (\n <MessageWrapper data-test={dataTest ? dataTest : \"notification\"}>\n {message}\n </MessageWrapper>\n );\n};\n\nconst styleDescription = (\n description: undefined | string | JSX.Element,\n): undefined | JSX.Element => {\n if (!description) {\n return undefined;\n }\n return <DescriptionWrapper>{description}</DescriptionWrapper>;\n};\n\nconst messageWithCount = (\n key: string | undefined,\n message: string | JSX.Element,\n dataTest?: string,\n) => {\n let updatedMessage = message;\n if (key) {\n const count = (activeNotifications.get(key)?.count ?? 0) + 1;\n activeNotifications.set(key, { count: count, message });\n if (count > 1 && isString(message)) {\n // If message is a string, add count to message\n updatedMessage = `${message} (${count} times)`;\n }\n }\n return styleMessage(updatedMessage, dataTest);\n};\n\n/**\n * When a Key is used,\n * duplicate notifications are not shown but the timeout is added to the first notification.\n * @returns A string key based on inputs\n */\nconst getKey = (\n type: string,\n message: string | JSX.Element,\n description: string | JSX.Element | undefined,\n duration: number | undefined,\n) => {\n return isString(message)\n ? `${type}--${String(message)}--${description}--${duration}`\n : undefined;\n};\n\nconst removeNotificationsWithKey = (key: string) => {\n document\n .querySelectorAll(`[data-testid=\"notification_${key}\"]`)\n .forEach((el) => {\n el.remove();\n });\n};\n\nconst attrSafeKey = (str: string) => {\n return str.replace(/\\W+/g, \"_\");\n};\n\nconst getIcon = (type: NotificationType) => {\n let icon: React.ReactNode;\n let color: string;\n switch (type) {\n case \"success\":\n icon = <SuccessIcon />;\n color = colors.SUCCESS;\n break;\n case \"error\":\n icon = <ErrorIcon />;\n color = colors.DANGER;\n break;\n case \"info\":\n icon = <InfoIcon />;\n color = colors.INFO;\n break;\n case \"warning\":\n icon = <WarningIcon />;\n color = colors.WARNING;\n break;\n }\n return <StatusIconWrapper color={color}>{icon}</StatusIconWrapper>;\n};\n\nfunction onAlertClose(key: string | undefined) {\n if (key) {\n activeNotifications.delete(key);\n }\n}\n\ntype Position = NonNullable<ToastT[\"position\"]>;\n\nconst positionToPlacement: Record<NotificationPosition, Position> = {\n [NotificationPosition.bottom]: \"bottom-center\",\n [NotificationPosition.top]: \"top-center\",\n [NotificationPosition.topLeft]: \"top-left\",\n [NotificationPosition.topRight]: \"top-right\",\n [NotificationPosition.bottomLeft]: \"bottom-left\",\n [NotificationPosition.bottomRight]: \"bottom-right\",\n} as const;\n\nexport function sendNotification({\n message,\n description,\n duration,\n key = getKey(\"success\", message, description, duration),\n placement = NotificationPosition.bottomRight,\n style,\n dataTest,\n type,\n}: NotificationConfig) {\n const icon = getIcon(type);\n\n const handleClose = () => {\n onAlertClose(key);\n if (key) {\n removeNotificationsWithKey(attrSafeKey(`notification-${key}`));\n }\n };\n\n if (key) {\n toast.dismiss(key);\n removeNotificationsWithKey(attrSafeKey(`notification-${key}`));\n }\n\n const position = positionToPlacement[placement];\n\n toast.success(messageWithCount(key, message, dataTest), {\n id: key,\n description: styleDescription(description),\n icon,\n duration: duration ? duration * 1000 : undefined,\n position: position,\n className: CLASS_NAMES.NOTIFICATION,\n style: style,\n onDismiss: handleClose,\n onAutoClose: handleClose,\n });\n}\n","export const generateId = () => {\n return Math.random().toString(36).substring(2, 15);\n};\n","import { makeAutoObservable } from \"mobx\";\n\n/**\n * Store for managing embed properties and events.\n * Used when the library is embedded in an external application (third-party embedding).\n *\n * Properties can be set by the parent window via postMessage, and events can be\n * emitted back to the parent window.\n */\nclass EmbedStore {\n properties: Record<string, unknown> = {};\n\n constructor() {\n makeAutoObservable(this);\n }\n\n /**\n * Update the embed properties. Called when the parent window sends updated properties.\n */\n setProperties(properties: Record<string, unknown>) {\n this.properties = properties;\n }\n\n /**\n * Emit an event to the parent window.\n * The parent can listen for these events using window.addEventListener(\"message\", ...).\n */\n emitEvent(eventName: string, payload: Record<string, unknown> = {}) {\n if (typeof window === \"undefined\" || window.parent === window) {\n // Not in an iframe or SSR environment\n return;\n }\n\n window.parent.postMessage(\n {\n type: \"embed-emit-event\",\n payload: { eventName, payload },\n },\n \"*\",\n );\n }\n\n /**\n * Typed helper for the platform-reserved\n * `superblocks:integration-auth-error` event. Emitted when an SDK API\n * execution fails the integration-auth gate (either reactively from a\n * 401/403 response or proactively from the embed shell). Hosts subscribe\n * via the embed SDK's `onEvent` and render their own connect/retry UX.\n *\n * `status` is the HTTP status that triggered the emit (401 or 403 for\n * reactive emits; the embed shell uses 401 for its proactive emit).\n * `integrationIds` are scoped to the integrations the host should drive\n * reauth for, so a host with multiple integrations can target the right\n * one.\n */\n emitIntegrationAuthError(payload: {\n apiId: string;\n integrationIds: string[];\n status: number;\n message: string;\n }) {\n this.emitEvent(\"superblocks:integration-auth-error\", payload);\n }\n}\n\nexport const embedStore = new EmbedStore();\n","export const AppMode = {\n EDIT: \"EDIT\",\n PUBLISHED: \"PUBLISHED\",\n PREVIEW: \"PREVIEW\",\n} as const;\n\nexport type AppMode = (typeof AppMode)[keyof typeof AppMode];\n","import { makeAutoObservable, reaction, toJS } from \"mobx\";\nimport {\n createContext,\n useCallback,\n useContext,\n useMemo,\n useSyncExternalStore,\n} from \"react\";\n\nimport { URL_PARAMS } from \"@superblocksteam/library-shared\";\nimport type { Profile } from \"@superblocksteam/shared\";\n\nimport { editorBridge } from \"../../edit-mode/superblocks-editor-bridge.js\";\nimport type { AppMode } from \"./scope/types\";\n\ntype User = {\n name: string;\n email: string;\n id: string;\n groups: Group[];\n username: string;\n metadata: Record<string, unknown>;\n};\n\ntype Group = {\n id: string;\n name: string;\n size: number;\n};\n\n/**\n * A data tag (formerly \"profile\") representing a data segment such as Staging or Production.\n *\n * Key fields:\n * - `key` — unique identifier, pass to `setDataTag()`\n * - `displayName` — human-readable label for UI display (there is no `name` field)\n * - `description` — optional description of the tag\n * - `type` — `\"RESERVED\"` or `\"CUSTOM\"`\n */\nexport type DataTag = Profile;\n\nexport type DataTags = {\n available: DataTag[];\n selected?: DataTag;\n default: DataTag;\n};\n\n/** @deprecated Use DataTags instead */\ntype Profiles = DataTags;\n\nexport class SuperblocksAppContext {\n private context?: {\n user?: User;\n groups?: Group[];\n selectedProfileId?: string;\n profiles?: Profiles;\n viewMode?: any;\n app?: {\n id: string;\n name: string;\n };\n };\n\n constructor() {\n makeAutoObservable(this);\n }\n\n get user() {\n return this.context?.user;\n }\n\n get groups() {\n return this.context?.groups;\n }\n\n get selectedProfile() {\n return this.context?.profiles?.selected;\n }\n\n get profiles() {\n return this.context?.profiles;\n }\n\n setProfile(profileKey: string) {\n const profile = this.context?.profiles?.available.find(\n (profile) => profile.key === profileKey,\n );\n if (profile && this.context?.profiles) {\n this.context.profiles.selected = profile;\n\n // Notify UI to update Redux profiles so agent URLs are updated\n if (typeof window !== \"undefined\" && window.parent !== window) {\n try {\n // Serialize profiles to plain objects for postMessage (Profile objects may contain non-cloneable MobX observables)\n const serializeProfile = (p: Profile) => toJS(p);\n\n editorBridge.updateProfiles({\n available: this.context.profiles.available.map(serializeProfile),\n selected: serializeProfile(profile),\n default: serializeProfile(this.context.profiles.default),\n });\n } catch (error) {\n console.error(\n \"[SuperblocksAppContext] Failed to sync profile change to parent window:\",\n error,\n );\n }\n }\n } else if (!profile || !this.context?.profiles) {\n throw new Error(`Profile ${profileKey} not found`);\n }\n }\n\n updateContext(context: Partial<SuperblocksAppContext>) {\n this.context = {\n ...this.context,\n ...context,\n };\n }\n\n getGlobal() {\n return this.context;\n }\n}\n\nexport const context = new SuperblocksAppContext();\n\nconst SuperblocksContext = createContext<SuperblocksAppContext>(context);\n\nexport function SuperblocksContextProvider({\n children,\n value: contextOverride,\n}: {\n children: React.ReactNode;\n value?: SuperblocksAppContext;\n}) {\n if (contextOverride) {\n return (\n <SuperblocksContext.Provider value={contextOverride}>\n {children}\n </SuperblocksContext.Provider>\n );\n }\n\n return (\n <SuperblocksContext.Provider value={context}>\n {children}\n </SuperblocksContext.Provider>\n );\n}\n\nexport function useSuperblocksContext() {\n return useContext(SuperblocksContext);\n}\n\nexport function useSuperblocksUser() {\n const context = useSuperblocksContext();\n const user = useSyncExternalStore(\n (onStoreChange) => {\n return reaction(() => context.user, onStoreChange);\n },\n () => context.user,\n () => context.user,\n );\n\n const cleanedUser = useMemo(() => toJS(user), [user]);\n return cleanedUser;\n}\n\nexport function useSuperblocksGroups() {\n const context = useSuperblocksContext();\n const groups = useSyncExternalStore(\n (onStoreChange) => {\n return reaction(() => context.groups, onStoreChange);\n },\n () => context.groups,\n () => context.groups,\n );\n\n const cleanedGroups = useMemo(() => toJS(groups), [groups]);\n return cleanedGroups;\n}\n\nexport function useSuperblocksDataTags() {\n const context = useSuperblocksContext();\n const dataTags = useSyncExternalStore(\n (onStoreChange) => {\n return reaction(() => context.profiles, onStoreChange);\n },\n () => context.profiles,\n () => context.profiles,\n );\n const cleanedDataTags = useMemo(() => toJS(dataTags), [dataTags]);\n const setDataTag = useCallback(\n (dataTagKey: string) => {\n context.setProfile(dataTagKey);\n },\n [context],\n );\n return { dataTags: cleanedDataTags, setDataTag };\n}\n\n/** @deprecated Use useSuperblocksDataTags instead */\nexport function useSuperblocksProfiles() {\n const { dataTags, setDataTag } = useSuperblocksDataTags();\n return { profiles: dataTags, setProfile: setDataTag };\n}\n\nlet appMode: AppMode | undefined;\n\nexport function getAppMode(): AppMode | undefined {\n if (!appMode) {\n appMode = new URL(window.location.href).searchParams.get(\n URL_PARAMS.appMode,\n ) as AppMode | undefined;\n if (!appMode) {\n console.warn(\"No app mode found in URL\");\n }\n }\n return appMode;\n}\n","// TODO(code-mode): Remove import from edit-mode\nimport { editorBridge } from \"../../../edit-mode/superblocks-editor-bridge.js\";\nimport { isEmbeddedBySuperblocksFirstParty } from \"./iframe.js\";\n\nconst EMBED_STRING = `embedded-`;\n\nlet promiseCount = 0;\nconst resolverMap = new Map<string, (...args: any[]) => any>();\nconst rejectorMap = new Map<string, (...args: any[]) => any>();\n\nconst multiUseCallbacks = new Map<string, (...args: any[]) => any>();\n\nexport function addNewPromise(\n resolver: (...args: any[]) => any,\n isMultiUse = false,\n rejecter?: (...args: any[]) => any,\n) {\n const promiseId = `${\n isEmbeddedBySuperblocksFirstParty() ? EMBED_STRING : \"\"\n }p${++promiseCount}`;\n resolverMap.set(promiseId, resolver);\n if (isMultiUse) {\n multiUseCallbacks.set(promiseId, resolver);\n }\n if (rejecter) {\n rejectorMap.set(promiseId, rejecter);\n }\n return promiseId;\n}\n\nexport function resolveById(id: string, payload: any) {\n const isEmbedId = id.startsWith(EMBED_STRING);\n if (\n (isEmbeddedBySuperblocksFirstParty() && !isEmbedId) ||\n (!isEmbeddedBySuperblocksFirstParty() && isEmbedId)\n ) {\n editorBridge.resolvePromise(id, payload);\n } else {\n try {\n const resolver = resolverMap.get(id);\n if (!resolver) {\n throw new Error(`Promise not found for id ${id}`);\n }\n resolver(payload);\n if (!multiUseCallbacks.has(id)) {\n resolverMap.delete(id);\n rejectorMap.delete(id);\n }\n } catch (e) {\n console.log(\"[internal] [resolveById] Error resolving promise\", e);\n }\n }\n}\n\nexport function rejectById(id: string, payload: any) {\n const isEmbedId = id.startsWith(EMBED_STRING);\n if (\n (isEmbeddedBySuperblocksFirstParty() && !isEmbedId) ||\n (!isEmbeddedBySuperblocksFirstParty() && isEmbedId)\n ) {\n editorBridge.rejectPromise(id, payload);\n } else {\n try {\n const rejecter = rejectorMap.get(id);\n if (!rejecter) {\n throw new Error(`Promise not found for id ${id}`);\n }\n rejecter(payload);\n if (!multiUseCallbacks.has(id)) {\n resolverMap.delete(id);\n rejectorMap.delete(id);\n }\n } catch (e) {\n console.log(\"[internal] [rejectById] Error rejecting promise\", e);\n }\n }\n}\n","type RefResult = {\n hardRef?: object;\n weakRef: WeakRef<object>;\n clearTimer?: ReturnType<typeof setTimeout>;\n};\n\nclass ApiHmrTracker {\n static CLEAR_REF_DELAY = 180e3; // 3 minutes\n\n private reloadCount: number = 0;\n private propagatedReloadCount: number = 0; // acts like a watermark to indicate the highest reload count that has been processed by React\n\n private seenHashes: Set<string> = new Set();\n private lastResultByHash: Record<string, RefResult> = {};\n\n private clearRefAfterDelay(value: RefResult) {\n clearTimeout(value.clearTimer);\n value.clearTimer = setTimeout(() => {\n value.clearTimer = undefined;\n delete value.hardRef;\n }, ApiHmrTracker.CLEAR_REF_DELAY);\n }\n\n private getAndRefreshResult(callHash: string) {\n const lastResult = this.lastResultByHash[callHash];\n if (!lastResult) {\n return null;\n }\n\n const result = lastResult.hardRef ?? lastResult.weakRef.deref();\n if (result) {\n this.clearRefAfterDelay(lastResult);\n return result;\n }\n\n return null;\n }\n\n // should skip if an only if all of the following are true:\n // - we've already seen this call hash (that means the API has executed already)\n // - the result is still valid (we have a valid cache entry to return)\n // - the reload count is not the same as the propagated reload count (AKA - we're likely in the middle of an HMR update)\n public shouldSkipRun(callHash: string) {\n if (!this.seenHashes.has(callHash)) {\n this.seenHashes.add(callHash);\n return false;\n }\n\n const result = this.getAndRefreshResult(callHash);\n // stored result has expired and GC'd so API must be re-run\n if (!result) {\n return false;\n }\n\n // finally, check if we're likely in the middle of an HMR update\n return this.propagatedReloadCount !== this.reloadCount;\n }\n\n public getCachedResult(callHash: string) {\n return this.getAndRefreshResult(callHash);\n }\n\n public setResult(callHash: string, result: object) {\n this.lastResultByHash[callHash] = {\n weakRef: new WeakRef(result),\n hardRef: result,\n };\n this.clearRefAfterDelay(this.lastResultByHash[callHash]);\n }\n\n public incReloadCount() {\n this.reloadCount++;\n }\n\n public dontSkipUntilNextReload() {\n this.propagatedReloadCount = Math.max(\n this.propagatedReloadCount,\n this.reloadCount,\n );\n }\n\n private mountLikeTimer: ReturnType<typeof setTimeout> | null = null;\n\n public reportJSXActivity() {\n const reloadCount = this.reloadCount;\n if (!this.mountLikeTimer) {\n this.mountLikeTimer = setTimeout(() => {\n requestIdleCallback(\n () => {\n this.propagatedReloadCount = Math.max(\n this.propagatedReloadCount,\n reloadCount,\n );\n this.mountLikeTimer = null;\n },\n { timeout: 50 }, // useful so this does not hang forever if the user is tabbed away\n );\n }, 0);\n }\n // then there is already a propagation about to happen, so don't do anything\n }\n}\n\nconst tracker = new ApiHmrTracker();\n\nif (import.meta.hot) {\n import.meta.hot.on(\"vite:beforeUpdate\", () => {\n tracker.incReloadCount();\n });\n}\n\nexport default tracker;\n","import { propagation, trace, context, ROOT_CONTEXT } from \"@opentelemetry/api\";\nimport type { Context, Span } from \"@opentelemetry/api\";\n\nimport { getTracer } from \"../utils.js\";\n\nexport function getContextFromTraceHeaders(\n traceHeaders: Record<string, string>,\n): Context {\n let parentContext = context.active();\n\n try {\n parentContext = propagation.extract(context.active(), traceHeaders);\n } catch (error) {\n console.warn(\n \"Failed to extract parent context from headers\",\n traceHeaders,\n error,\n );\n }\n\n return parentContext;\n}\n\nexport function createIframeSpan(\n name: string,\n attributes: Record<string, any>,\n parentContext?: Context,\n) {\n const tracer = getTracer(\"superblocks-iframe\");\n return tracer.startSpan(name, { attributes }, parentContext);\n}\n\nexport function getTraceContextHeadersFromSpan(\n span: Span,\n): Record<string, string> {\n const traceContextHeaders = {};\n const contextWithSpan = trace.setSpan(ROOT_CONTEXT, span);\n propagation.inject(contextWithSpan, traceContextHeaders);\n return traceContextHeaders;\n}\n","import { context } from \"@opentelemetry/api\";\n\nimport {\n ViewMode,\n SUPERBLOCKS_REQUEST_ID_HEADER,\n SUPERBLOCKS_AUTHORIZATION_HEADER,\n decodeBytestrings,\n} from \"@superblocksteam/shared\";\nimport { ApiResponseType } from \"@superblocksteam/shared\";\nimport type { Agent } from \"@superblocksteam/shared\";\n\nimport {\n getContextFromTraceHeaders,\n createIframeSpan,\n getTraceContextHeadersFromSpan,\n} from \"../../../tracing/context-utils.js\";\nimport { cleanObject } from \"../../../utils/clean-object.js\";\nimport { generateId } from \"../../../utils/generate-id.js\";\nimport { SystemErrorType } from \"../types.js\";\nimport type {\n ApiV2ExecutionRequest,\n ApiV2ExecutionResponse,\n ExecutionEvent,\n ExecutionResponse,\n StreamEvent,\n} from \"../types.js\";\n\nexport type ExecuteV2ApiParams = {\n body: ApiV2ExecutionRequest;\n apiName?: string;\n environment: string;\n eventType: string; // TODO(code-mode/api) figure out if we need a type for this, probably not\n notifyOnSystemError: boolean;\n // organization: Organization;\n responseType: ApiResponseType;\n onMessage?: (message: any) => void;\n processStreamEvents?: (event: StreamEvent) => void;\n controlFlowOnlyFiles?: FileRequestParam[];\n abortController?: AbortController;\n baseUrl: string;\n agents: Array<Agent>;\n viewMode: ViewMode;\n accessToken: string;\n token: string;\n maxResponseBytes?: number;\n traceHeaders?: Record<string, string>;\n};\n\nexport async function executeV2Api(\n params: ExecuteV2ApiParams,\n): Promise<ExecutionResponse | undefined | void> {\n const {\n body,\n apiName,\n controlFlowOnlyFiles,\n notifyOnSystemError,\n eventType,\n onMessage,\n processStreamEvents,\n responseType,\n abortController,\n baseUrl,\n // agents,\n // organization,\n viewMode,\n accessToken,\n token,\n maxResponseBytes,\n traceHeaders,\n } = params;\n\n let parentContext = context.active();\n\n if (traceHeaders) {\n parentContext = getContextFromTraceHeaders(traceHeaders);\n }\n\n let applicationId = \"unknown\";\n if (\"fetchByPath\" in body) {\n applicationId = body.fetchByPath.applicationId;\n }\n const span = createIframeSpan(\n \"iframe_execute_v2_api\",\n {\n \"api-name\": apiName || \"unknown\",\n \"application-id\": applicationId,\n event_type: eventType,\n response_type: responseType,\n view_mode: viewMode,\n },\n parentContext,\n );\n\n try {\n // Clean the body to handle proxy objects before stringifying\n let cleanedBody: Record<string, any>;\n try {\n cleanedBody = cleanObject(body) as Record<string, any>;\n } catch {\n cleanedBody = structuredClone(body);\n }\n\n if (controlFlowOnlyFiles && controlFlowOnlyFiles.length > 0) {\n cleanedBody = {\n ...cleanedBody,\n files: controlFlowOnlyFiles,\n };\n }\n\n // TODO(code-mode/api) deployed mode\n\n // Inject current trace context for server continuation\n const traceContextHeaders = getTraceContextHeadersFromSpan(span);\n\n const init: RequestInit = {\n method: HttpMethod.Post,\n body: JSON.stringify(cleanedBody),\n signal: abortController?.signal,\n headers: {\n [SUPERBLOCKS_AUTHORIZATION_HEADER]: `Bearer ${accessToken}`,\n Authorization: `Bearer ${token}`,\n [SUPERBLOCKS_REQUEST_ID_HEADER]: generateId(),\n // Include trace context headers for distributed tracing\n ...traceContextHeaders,\n },\n credentials: \"include\" as RequestCredentials,\n };\n\n const result =\n responseType === ApiResponseType.STREAM\n ? await fetchServerStream({\n augmentedInit: init,\n fullUrl: baseUrl,\n // TODO(code-mode/api)\n timeoutId: setTimeout(() => {}, 1000),\n onMessage,\n processStreamEvents,\n maxResponseBytes,\n })\n : await fetchServer({\n augmentedInit: init,\n fullUrl: baseUrl,\n // TODO(code-mode/api)\n timeoutId: setTimeout(() => {}, 1000),\n maxResponseBytes,\n });\n\n return result as ExecutionResponse | undefined;\n } catch (err) {\n const message = `Failed to execute ${apiName || \"API\"}. ${err}`;\n\n // https://app.clickup.com/t/8650101/EG-16438\n //this corresponds to \"signal is aborted without reason\" which we should not surface as it happens when switching pages\n const suppressError =\n viewMode !== ViewMode.EDITOR && (err as any)?.code === 20;\n\n if (notifyOnSystemError && !suppressError) {\n // TODO(code-mode/api)\n // sendErrorUINotification({\n // message,\n // });\n console.log(`[internal] [executeV2Api] ${message}`);\n }\n\n if (err instanceof ResponseSizeLimitError) {\n span.recordException(err);\n span.setAttributes({\n \"response_size_limit.exceeded\": true,\n \"response_size_limit.limit_bytes\": err.limitBytes,\n });\n console.warn(\n \"[internal] [executeV2Api] orchestrator /execute response size limit exceeded\",\n {\n apiName: apiName ?? \"unknown\",\n applicationId,\n limitBytes: err.limitBytes,\n },\n );\n }\n\n // Preserve HTTP status code from HttpError if available\n const statusCode =\n err instanceof HttpError\n ? err.code\n : err instanceof ResponseSizeLimitError\n ? 413\n : undefined;\n\n let errorType: SystemErrorType = SystemErrorType.GENERAL;\n const errorMessage = err instanceof Error ? err.message : String(err);\n const errorConstructorName = (err as any)?.constructor?.name;\n\n const isTypeError =\n err instanceof TypeError || errorConstructorName === \"TypeError\";\n const hasNetworkErrorMessage =\n errorMessage.includes(\"Failed to fetch\") ||\n errorMessage.includes(\"network error\") ||\n errorMessage.includes(\"NetworkError\") ||\n (errorMessage.includes(\"TypeError\") && errorMessage.includes(\"fetch\")) ||\n errorMessage.includes(\"ERR_NETWORK\") ||\n errorMessage.includes(\"ERR_INTERNET_DISCONNECTED\") ||\n errorMessage.includes(\"ERR_CONNECTION_REFUSED\") ||\n errorMessage.includes(\"ERR_CONNECTION_RESET\") ||\n errorMessage.includes(\"ERR_CONNECTION_TIMED_OUT\") ||\n errorMessage.includes(\"Failed to connect\") ||\n errorMessage.includes(\"network issue\") ||\n errorMessage.includes(\"timed out\");\n\n if (isTypeError || hasNetworkErrorMessage) {\n errorType = SystemErrorType.NETWORK;\n } else if (err instanceof HttpError) {\n errorType = SystemErrorType.HTTP;\n }\n\n return {\n systemError: message,\n statusCode,\n errorType,\n };\n } finally {\n span.end();\n }\n}\n\nconst HttpMethod = {\n Get: \"GET\",\n Post: \"POST\",\n Put: \"PUT\",\n Patch: \"PATCH\",\n Delete: \"DELETE\",\n} as const;\n\ntype HttpMethodName = (typeof HttpMethod)[keyof typeof HttpMethod];\n\ntype FileRequestParam = {\n originalName: string;\n buffer: string; // base64 encoded string\n encoding: \"base64\";\n mimeType: string;\n size: string;\n};\n\nconst cancelReaderBestEffort = async (\n reader: ReadableStreamDefaultReader<Uint8Array>,\n) => {\n await reader.cancel().catch(() => undefined);\n};\n\nconst isResponseSizeLimitEnabled = (\n maxResponseBytes: number | undefined,\n): maxResponseBytes is number =>\n maxResponseBytes !== undefined &&\n Number.isFinite(maxResponseBytes) &&\n maxResponseBytes > 0;\n\nconst stream = async ({\n url,\n headers,\n body,\n onMessage,\n onComplete,\n onError,\n defaultError,\n method,\n baseUrl = \"/api/\",\n signal,\n init: overrideInit,\n maxResponseBytes,\n}: {\n url: string;\n init?: RequestInit;\n headers?: Record<string, string>;\n body?: Record<string, any>;\n onMessage: (message: any) => void;\n onComplete: () => void;\n onError: (error: string, statusCode?: number) => void;\n defaultError?: string;\n method?: HttpMethodName;\n baseUrl?: string;\n signal?: AbortSignal;\n maxResponseBytes?: number;\n}): Promise<void> => {\n const init: RequestInit = overrideInit ?? {\n body: JSON.stringify(body),\n headers,\n method,\n };\n try {\n const response = await fetch(`${baseUrl}${url}`, init);\n\n if (!response.ok) {\n try {\n const parsed = await readJsonResponseWithLimit(\n response,\n maxResponseBytes,\n );\n\n throw new HttpError(\n response.status,\n !response.status || response.status >= 500,\n parsed?.error?.message ??\n parsed?.responseMeta?.error?.message ??\n defaultError,\n );\n } catch (e) {\n if (e instanceof HttpError || e instanceof ResponseSizeLimitError) {\n throw e;\n }\n //response cannot be parsed to json, throwing http error as it is the cause\n throw new HttpError(\n response.status,\n !response.status || response.status >= 500,\n response.statusText,\n );\n }\n }\n if (!response.body) {\n return;\n }\n const reader = response.body.getReader();\n const decoder = new TextDecoder();\n let done = false;\n let totalBytes = 0;\n\n let lastChunk = \"\";\n while (!done) {\n if (signal && signal.aborted) {\n return; // Stop processing if the fetch was cancelled\n }\n const { value, done: readerDone } = await reader.read();\n if (value) {\n totalBytes += value.byteLength;\n if (\n isResponseSizeLimitEnabled(maxResponseBytes) &&\n totalBytes > maxResponseBytes\n ) {\n await cancelReaderBestEffort(reader);\n throw new ResponseSizeLimitError(maxResponseBytes);\n }\n }\n const chunk = lastChunk + decoder.decode(value);\n const messages = chunk.split(\"\\n\");\n\n let jsonValues: { error?: { message: string } }[] = [];\n try {\n jsonValues = messages\n .filter(Boolean)\n .map((message) => JSON.parse(message.trim()));\n // Reset the last chunk if we were able to parse the message\n lastChunk = \"\";\n } catch (e) {\n // If we can't parse the message, it's probably because we only got a partial message\n // Append the chunk to the last chunk and try again next time\n lastChunk = chunk;\n\n // If we fail to parse and the reader is done, then we should throw an error\n // as we won't be able to parse the message\n if (readerDone) {\n throw e;\n }\n }\n\n for (const jsonValue of jsonValues.filter(Boolean)) {\n if (jsonValue?.error) {\n onError(jsonValue.error.message ?? defaultError);\n return;\n }\n onMessage(jsonValue);\n }\n\n done = readerDone && lastChunk === \"\";\n }\n } catch (e: HttpError | TypeError | ResponseSizeLimitError | any) {\n if (e.name === \"AbortError\") {\n console.log(\"[internal] [stream] Fetch was cancelled\");\n } else if (e instanceof ResponseSizeLimitError) {\n throw e;\n } else {\n onError(e.message ?? defaultError, e.code);\n }\n } finally {\n onComplete();\n }\n};\n\ninterface BaseFetchOptions {\n augmentedInit: RequestInit;\n timeoutId: ReturnType<typeof setTimeout>;\n body?: Record<string, any>;\n maxResponseBytes?: number;\n path?: string;\n // TODO(code-mode/api)\n // diagnosticMetadata?: AgentDiagnosticMetadata;\n // errorHandlingOptions?: ErrorHandlingOptions;\n}\n\ninterface FetchOptions extends BaseFetchOptions {\n fullUrl: string;\n}\n\ninterface StreamingFetchOptions extends FetchOptions {\n onMessage?: (message: any) => void;\n processStreamEvents?: (event: any) => void;\n}\n\nconst fetchServerStream = async ({\n augmentedInit,\n fullUrl,\n timeoutId,\n onMessage,\n processStreamEvents,\n maxResponseBytes,\n}: StreamingFetchOptions): Promise<void> => {\n const handleMessage = (message: any) => {\n if (message?.result?.event?.data) {\n // eslint-disable-next-line @typescript-eslint/no-unused-expressions\n onMessage && onMessage(message.result.event.data);\n } else if (message?.result?.event?.start || message?.result?.event?.end) {\n // if the message is a start or end message, we want to process it so we can show the live execution results\n // eslint-disable-next-line @typescript-eslint/no-unused-expressions\n processStreamEvents && processStreamEvents(message);\n }\n };\n\n const onComplete = () => {\n clearTimeout(timeoutId);\n };\n\n const onError = (error: string, statusCode?: number) => {\n // Create error and throw directly - let executeV2Api handle it\n // TODO(Mark): Error handling should not be special for block outputs -\n // we should treat streaming errors the same as non-streaming errors\n if (statusCode != null) {\n throw new HttpError(statusCode, !statusCode || statusCode >= 500, error);\n } else {\n throw new TypeError(error);\n }\n };\n\n return stream({\n url: fullUrl,\n init: augmentedInit,\n onMessage: handleMessage,\n onComplete,\n onError,\n baseUrl: \"\",\n signal: augmentedInit?.signal ?? undefined,\n maxResponseBytes,\n });\n};\n\nconst getErrorMessageFromObject = (message: object) => {\n const messageJSONString = JSON.stringify(message);\n const regex = /\"message\"\\s*:\\s*\"([^\"]*)\"/;\n const match = regex.exec(messageJSONString);\n return match ? match[1] : messageJSONString;\n};\n\nconst fetchServer = <TResult>({\n augmentedInit,\n fullUrl,\n timeoutId,\n maxResponseBytes,\n // errorHandlingOptions,\n}: FetchOptions): Promise<TResult> => {\n return fetch(fullUrl, augmentedInit)\n .then(async (response) => {\n try {\n if (response.status === 204) {\n return null;\n }\n const json = await readJsonResponseWithLimit(\n response,\n maxResponseBytes,\n );\n if (response.ok && json) {\n if (json.data == null) {\n return json; // v2 API endpoints do not wrap\n }\n return json.data as TResult;\n } else {\n let message = json.responseMeta?.error?.message ?? json?.message;\n if (typeof message === \"object\") {\n message = getErrorMessageFromObject(message);\n }\n\n throw new HttpError(\n response.status,\n !response.status || response.status >= 500,\n message,\n );\n }\n } catch (e) {\n //response with json parsed, but has error code\n if (e instanceof HttpError || e instanceof ResponseSizeLimitError) {\n throw e;\n }\n //response cannot be parsed to json, throwing http error as it is the cause\n throw new HttpError(\n response.status,\n !response.status || response.status >= 500,\n response.statusText,\n );\n }\n })\n .finally(() => clearTimeout(timeoutId));\n};\n\nclass HttpError extends Error {\n code: number;\n critical: boolean;\n\n constructor(code: number, critical = false, m?: string) {\n super(m);\n this.code = code;\n this.critical = critical;\n }\n}\n\n/** Byte budget for a single value captured into an editor API run record. */\nexport const MAX_EDITOR_RUN_RECORD_RESPONSE_BYTES = 1_000_000; // 1 MB\n\nconst RUN_RECORD_TRUNCATION_PREVIEW_CHARS = 4096;\n\n/** Why a run-record value was replaced with a bounded marker. */\nexport type RunRecordTruncationReason = \"size\" | \"unserializable\";\n\nexport interface BoundedRunRecordValue {\n value: unknown;\n truncated: boolean;\n reason?: RunRecordTruncationReason;\n}\n\n/**\n * Serializes a value for the run-record size probe, tolerating inputs that plain\n * `JSON.stringify` rejects but `structuredClone` (the postMessage transport)\n * accepts: `BigInt` (rendered as a `\"<n>n\"` string) and repeated/circular\n * references (collapsed to a `\"[Circular]\"` marker). Returning a JSON-safe string\n * lets the caller preserve sibling fields instead of blanking the whole value,\n * and keeps the stored inspector copy safe for the inspector's own\n * `JSON.stringify` render.\n *\n * A DAG (the same object reached from two branches) is treated like a cycle and\n * its repeats collapse to the marker; that only under-counts size for the probe\n * and never drops data the app relies on.\n */\nconst serializeRunRecordValueTolerant = (value: unknown): string => {\n const seen = new WeakSet<object>();\n return JSON.stringify(value, (_key, val) => {\n if (typeof val === \"bigint\") {\n return `${val.toString()}n`;\n }\n if (typeof val === \"object\" && val !== null) {\n if (seen.has(val)) {\n return \"[Circular]\";\n }\n seen.add(val);\n }\n return val;\n });\n};\n\n/**\n * Bounds a value captured into an editor API run record (its `response` or its\n * `inputs`). In edit mode these are forwarded to the parent editor (postMessage)\n * and retained per run for the run inspector; a large value (e.g. thousands of\n * rows) would be structured-cloned and accumulated, exhausting the editor tab's\n * memory. Only the editor's inspector copy is capped -- the app still receives\n * the full, untouched value. Mirrors the AI-service forward path, which already\n * caps outputs (see library-shared `socket.ts` output-truncated flag).\n *\n * `BigInt` / circular values are re-encoded to a JSON-safe form (siblings\n * preserved) rather than blanked, so a single `BigInt` or cycle no longer hides\n * the whole value; only a value that throws while serializing (e.g. a throwing\n * `toJSON`) is omitted. When `truncated` is true, `value` is a human-readable\n * marker STRING (a size preview, or an \"omitted\" notice), not the original\n * shape; `reason` distinguishes the two cases. Never throws.\n */\nexport const boundRunRecordValue = (value: unknown): BoundedRunRecordValue => {\n if (value == null) {\n return { value, truncated: false };\n }\n let serialized: string | undefined;\n // When true, `serialized` came from the tolerant serializer, so its JSON-safe\n // parsed form (siblings preserved) must be stored rather than the raw value --\n // the raw value may carry a BigInt/cycle the inspector's JSON.stringify render\n // cannot handle.\n let sanitized = false;\n try {\n serialized = JSON.stringify(value);\n } catch {\n try {\n serialized = serializeRunRecordValueTolerant(value);\n sanitized = true;\n } catch (err) {\n // A throwing toJSON / getter defeats even the tolerant serializer. This is\n // a probe for the inspector copy only, so we substitute a marker rather\n // than throw (throwing would abort the API run). The app's own copy of the\n // value is unaffected.\n console.warn(\n \"[api-utils] [boundRunRecordValue] value not serializable; omitting from editor run record:\",\n err instanceof Error ? err.message : String(err),\n );\n return {\n value:\n \"[Superblocks editor: value omitted from the run record -- not serializable. The full value is still available to your app.]\",\n truncated: true,\n reason: \"unserializable\",\n };\n }\n }\n if (serialized == null) {\n return { value, truncated: false };\n }\n const bytes = new TextEncoder().encode(serialized).byteLength;\n if (bytes <= MAX_EDITOR_RUN_RECORD_RESPONSE_BYTES) {\n // Under budget: pass the original through unchanged, unless it had to be\n // sanitized (BigInt/cycle) -- then store the JSON-safe form so the inspector\n // renders every field instead of blanking the whole value.\n return sanitized\n ? { value: JSON.parse(serialized), truncated: false }\n : { value, truncated: false };\n }\n // Leave a breadcrumb for the common (large-but-valid) case too, so a support\n // engineer debugging \"why is my run inspector showing a marker\" has a\n // client-side log; previously only the unserializable branch logged.\n console.warn(\n `[api-utils] [boundRunRecordValue] value truncated from editor run record: ${bytes} bytes exceeds the ${MAX_EDITOR_RUN_RECORD_RESPONSE_BYTES}-byte inspector limit.`,\n );\n return {\n value: `[Superblocks editor: value truncated -- ${bytes} bytes exceeds the ${MAX_EDITOR_RUN_RECORD_RESPONSE_BYTES}-byte inspector limit. The full value is still available to your app; run the API to view it.]\\nPreview: ${serialized.slice(\n 0,\n RUN_RECORD_TRUNCATION_PREVIEW_CHARS,\n )}`,\n truncated: true,\n reason: \"size\",\n };\n};\n\nexport interface RunRecordStepLog {\n stepName: string;\n stdout?: string[];\n stderr?: string[];\n output?: unknown;\n error?: string;\n}\n\n/**\n * Bounds the step logs captured into an editor run record. Each step's `output`\n * (the step's return value -- for the final step this often mirrors the full API\n * result) and its `stdout`/`stderr` are capped the same way as the top-level\n * response. Only the editor copy is bounded; the app is unaffected. Never throws.\n *\n * The cap is PER FIELD, not per record: a single oversized step field is\n * bounded, but an API with many blocks each returning a just-under-budget\n * payload could still assemble an aggregate above the budget. This closes the\n * reported single-fetch case (one large response / terminal-step output);\n * bounding the aggregate across all step fields is a separate follow-up.\n *\n * `reuse` lets the caller supply an already-computed bound for a step whose\n * `output` is reference-equal to `reuse.value`. A single-fetch API's terminal\n * step output is the same object as the top-level response, so this avoids\n * serializing that (potentially multi-MB) payload a second time.\n */\nexport const boundRunRecordStepLogs = (\n stepLogs: RunRecordStepLog[] | undefined,\n reuse?: { value: unknown; bounded: BoundedRunRecordValue },\n): { stepLogs: RunRecordStepLog[] | undefined; truncated: boolean } => {\n if (!stepLogs?.length) {\n return { stepLogs, truncated: false };\n }\n let truncated = false;\n const bounded = stepLogs.map((step) => {\n const output =\n reuse && step.output === reuse.value\n ? reuse.bounded\n : boundRunRecordValue(step.output);\n const stdout = boundRunRecordValue(step.stdout);\n const stderr = boundRunRecordValue(step.stderr);\n if (output.truncated || stdout.truncated || stderr.truncated) {\n truncated = true;\n }\n return {\n ...step,\n output: output.value,\n stdout: stdout.truncated ? [String(stdout.value)] : step.stdout,\n stderr: stderr.truncated ? [String(stderr.value)] : step.stderr,\n };\n });\n return { stepLogs: bounded, truncated };\n};\n\nexport class ResponseSizeLimitError extends Error {\n constructor(public readonly limitBytes: number) {\n super(\n `Response blocked: exceeded orchestrator /execute response limit of ${limitBytes} bytes.`,\n );\n this.name = \"ResponseSizeLimitError\";\n }\n}\n\nexport const readTextResponseWithLimit = async (\n response: Response,\n maxResponseBytes?: number,\n): Promise<string> => {\n if (!response.body) {\n // Fetch responses may have a null body for bodyless statuses, HEAD, older\n // fetch polyfills, or test doubles. Preserve those paths, but still enforce\n // the cap when text() is available.\n const text = await response.text();\n if (\n isResponseSizeLimitEnabled(maxResponseBytes) &&\n new TextEncoder().encode(text).byteLength > maxResponseBytes\n ) {\n throw new ResponseSizeLimitError(maxResponseBytes);\n }\n return text;\n }\n\n const reader = response.body.getReader();\n const chunks: Uint8Array[] = [];\n let totalBytes = 0;\n\n while (true) {\n const { value, done } = await reader.read();\n if (done) {\n break;\n }\n if (!value) {\n continue;\n }\n\n totalBytes += value.byteLength;\n if (\n isResponseSizeLimitEnabled(maxResponseBytes) &&\n totalBytes > maxResponseBytes\n ) {\n await cancelReaderBestEffort(reader);\n throw new ResponseSizeLimitError(maxResponseBytes);\n }\n\n chunks.push(value);\n }\n\n const body = new Uint8Array(totalBytes);\n let offset = 0;\n for (const chunk of chunks) {\n body.set(chunk, offset);\n offset += chunk.byteLength;\n }\n\n return new TextDecoder().decode(body);\n};\n\nconst isLegacyJsonOnlyResponseMock = (\n response: Response,\n): response is Response & { json: () => Promise<unknown> } => {\n const maybeResponse = response as Partial<Response>;\n return (\n !maybeResponse.body &&\n typeof maybeResponse.text !== \"function\" &&\n typeof maybeResponse.json === \"function\"\n );\n};\n\nexport const readJsonResponseWithLimit = async <TResult = any>(\n response: Response,\n maxResponseBytes?: number,\n): Promise<TResult> => {\n if (isLegacyJsonOnlyResponseMock(response)) {\n // Existing unit tests use lightweight response mocks that only implement\n // json(); real fetch responses take the byte-counting path above.\n return response.json() as Promise<TResult>;\n }\n\n return JSON.parse(\n await readTextResponseWithLimit(response, maxResponseBytes),\n ) as TResult;\n};\n\nexport const parseStreamResult = (\n streamResult: Array<StreamEvent>,\n options?: {\n includeFinalOutput?: boolean;\n },\n): undefined | ApiV2ExecutionResponse => {\n if (!streamResult || !Array.isArray(streamResult) || !streamResult.length) {\n return;\n }\n const execution = streamResult[0].result.execution;\n const [errors, events] = streamResult.reduce(\n (accum: [{ message: string }[], ExecutionEvent[]], event) => {\n if (event.result.event.end && event.result.event.end.error) {\n accum[0].push(event.result.event.end.error);\n }\n accum[1].push(event.result.event);\n\n return accum;\n },\n [[], []],\n );\n const result: ApiV2ExecutionResponse = {\n execution,\n events,\n errors,\n status: \"STATUS_COMPLETED\",\n };\n\n if (options?.includeFinalOutput) {\n // Check for a Return block, which should be the api result rather than just the last block\n let returnBlockOutput: ApiV2ExecutionResponse[\"output\"];\n for (let i = 0; i < streamResult.length; i++) {\n const streamEvent = streamResult[i];\n if (\n streamEvent.result.event.type === \"BLOCK_TYPE_RETURN\" &&\n streamEvent.result.event.end\n ) {\n returnBlockOutput = streamEvent.result.event.end\n ?.output as ApiV2ExecutionResponse[\"output\"];\n break;\n }\n }\n if (returnBlockOutput) {\n result.output = returnBlockOutput;\n } else {\n const output = streamResult[streamResult.length - 1].result.event.end\n ?.output as ApiV2ExecutionResponse[\"output\"];\n result.output = output;\n }\n }\n\n return result;\n};\n\nexport const isApiV2ExecutionResponse = (\n response: ExecutionResponse | undefined | void,\n): response is ApiV2ExecutionResponse => {\n return !!response && \"output\" in response && response?.output?.result != null;\n};\n\nexport const decodeBytestringsInV2ExecutionResponse = (\n response: ExecutionResponse,\n) => {\n if (!isApiV2ExecutionResponse(response)) {\n return;\n }\n if (response.output) {\n response.output.result = decodeBytestrings(response.output.result, false);\n }\n if (Array.isArray(response.events)) {\n response.events.forEach((event) => {\n const typedEvent = event as ExecutionEvent;\n if (typedEvent?.end?.output?.result != null) {\n typedEvent.end.output.result = decodeBytestrings(\n typedEvent.end.output.result,\n false,\n );\n }\n });\n }\n};\n","import type { FileMetadataPrivate } from \"@superblocksteam/shared\";\n\ntype FileRequestParam = {\n originalName: string;\n buffer: string;\n encoding: \"base64\";\n mimeType: string;\n size: string;\n};\n\ntype FileLike = {\n name: string;\n size: number;\n type: string;\n lastModified: number;\n arrayBuffer?: () => Promise<ArrayBuffer>;\n};\n\nfunction isNativeFile(value: unknown): value is File {\n return typeof File !== \"undefined\" && value instanceof File;\n}\n\nfunction isFileLike(value: unknown): value is FileLike {\n if (isNativeFile(value)) {\n return true;\n }\n if (typeof value !== \"object\" || value == null) {\n return false;\n }\n\n return (\n typeof (value as Partial<FileLike>).name === \"string\" &&\n typeof (value as Partial<FileLike>).size === \"number\" &&\n typeof (value as Partial<FileLike>).type === \"string\" &&\n typeof (value as Partial<FileLike>).lastModified === \"number\" &&\n typeof (value as Partial<FileLike>).arrayBuffer === \"function\"\n );\n}\n\nfunction isPathOnlyFileDescriptor(\n value: unknown,\n): value is { path: string; relativePath?: string } {\n if (typeof value !== \"object\" || value == null) {\n return false;\n }\n\n return (\n typeof (value as { path?: unknown }).path === \"string\" &&\n typeof (value as { arrayBuffer?: unknown }).arrayBuffer !== \"function\"\n );\n}\n\nfunction bytesToBase64(bytes: Uint8Array): string {\n if (typeof Buffer !== \"undefined\") {\n return Buffer.from(bytes).toString(\"base64\");\n }\n\n let binary = \"\";\n const chunkSize = 0x8000;\n for (let i = 0; i < bytes.length; i += chunkSize) {\n binary += String.fromCharCode(...bytes.subarray(i, i + chunkSize));\n }\n return btoa(binary);\n}\n\nfunction getFileUploadId(\n file: Pick<FileLike, \"name\" | \"size\" | \"lastModified\">,\n): string {\n const name = file.name.replace(/[^a-zA-Z0-9.-]/g, \"_\");\n const size = file.size;\n const lastModified = file.lastModified;\n\n return `${name}-${size}-${lastModified}`;\n}\n\nfunction getFileInputData(\n f: Pick<FileLike, \"name\" | \"size\" | \"type\" | \"lastModified\">,\n): FileMetadataPrivate {\n const superblocksId = getFileUploadId(f);\n\n const nameParts = f.name.split(\".\");\n const extension = nameParts.length > 1 ? nameParts.pop() || \"\" : \"\";\n\n return {\n $superblocksId: superblocksId,\n name: f.name,\n extension,\n type: f.type,\n size: f.size,\n encoding: \"text\" as const,\n };\n}\n\nasync function formatFileForRequest(\n file: FileLike,\n fileId: string,\n): Promise<FileRequestParam> {\n const base64 =\n typeof file.arrayBuffer === \"function\"\n ? bytesToBase64(new Uint8Array(await file.arrayBuffer()))\n : await new Promise<string>((resolve, reject) => {\n const reader = new FileReader();\n reader.onload = () =>\n resolve((reader.result as string).split(\",\")[1]);\n reader.onerror = () =>\n reject(\n new Error(reader.error?.message || \"Unknown error reading file\"),\n );\n reader.readAsDataURL(file as unknown as Blob);\n });\n\n return {\n originalName: fileId,\n buffer: base64,\n encoding: \"base64\" as const,\n mimeType: file.type || \"application/octet-stream\",\n size: String(file.size),\n };\n}\n\nexport async function getInputsWithFileMetadata(\n inputs: Record<string, unknown>,\n): Promise<{\n inputs: Record<string, unknown>;\n files: Array<FileRequestParam>;\n}> {\n const filesForRequest: Record<string, FileRequestParam> = {};\n\n const processValue = async (value: unknown): Promise<unknown> => {\n // null is something we can send over the HTTP request, undefined is not, and Clark likes to write both\n // null and undefined interchangeably in it's code, so we just need to help it along here.\n if (value === undefined) {\n return null;\n }\n if (isFileLike(value)) {\n const inputData = getFileInputData(value);\n if (!filesForRequest[inputData.$superblocksId]) {\n filesForRequest[inputData.$superblocksId] = await formatFileForRequest(\n value,\n inputData.$superblocksId,\n );\n }\n return inputData;\n }\n if (isPathOnlyFileDescriptor(value)) {\n throw new Error(\n \"File upload inputs must be browser File objects (or compatible file-like objects with arrayBuffer()). Received a path-only file descriptor instead.\",\n );\n } else if (Array.isArray(value)) {\n return await Promise.all(value.map((item) => processValue(item)));\n } else if (\n typeof value === \"object\" &&\n value != null &&\n value.constructor === Object\n ) {\n return await processObject(value as Record<string, unknown>);\n }\n return value;\n };\n\n const processObject = async (\n obj: Record<string, unknown>,\n ): Promise<Record<string, unknown>> => {\n const result: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(obj)) {\n result[key] = await processValue(value);\n }\n return result;\n };\n\n const finalInputs = await processObject(inputs);\n return { inputs: finalInputs, files: Object.values(filesForRequest) };\n}\n","type StringEndsWithSlash = `${string}/`;\n\n/**\n * Ensures a base URL has a trailing slash for proper path joining.\n *\n * Without a trailing slash, the URL constructor treats the last segment as a file\n * and replaces it instead of appending:\n *\n * new URL(\"v2/execute\", \"https://example.com/opa\").href\n * = \"https://example.com/v2/execute\" (WRONG - /opa is replaced!)\n *\n * new URL(\"v2/execute\", \"https://example.com/opa/\").href\n * = \"https://example.com/opa/v2/execute\" (CORRECT)\n */\nexport function withTrailingSlash(baseUrl: string): StringEndsWithSlash {\n return baseUrl.endsWith(\"/\")\n ? (baseUrl as StringEndsWithSlash)\n : `${baseUrl}/`;\n}\n","import { action } from \"mobx\";\n\nimport {\n ApiResponseType,\n OrchestratorViewMode,\n SUPERBLOCKS_AUTHORIZATION_HEADER,\n SUPERBLOCKS_REQUEST_ID_HEADER,\n ViewMode,\n} from \"@superblocksteam/shared\";\n// TODO(code-mode): Remove import from edit-mode\nimport type {\n DeleteMeLibraryApi,\n ExecutionTimingBreakdown,\n SbApiRunOptions,\n} from \"@superblocksteam/library-shared/types\";\n\nimport { editorBridge } from \"../../../../edit-mode/superblocks-editor-bridge.js\";\nimport { sendNotification } from \"../../../user-facing/utils/notification.jsx\";\nimport { generateId } from \"../../../utils/generate-id.js\";\nimport { embedStore } from \"../../embed-store.js\";\nimport { isEditMode } from \"../../is-edit-mode.js\";\nimport { AppMode } from \"../../scope/types.js\";\nimport {\n context as superblocksContext,\n getAppMode,\n} from \"../../superblocks-context.js\";\nimport { addNewPromise } from \"../resolve-id-singleton.js\";\nimport type { RootStore } from \"../root-store.js\";\nimport type {\n StreamEvent,\n ExecutionResponse,\n ExecutionEvent,\n AgentInfo,\n} from \"../types.js\";\nimport ApiHmrTracker from \"./api-hmr-tracker.js\";\nimport {\n boundRunRecordStepLogs,\n boundRunRecordValue,\n decodeBytestringsInV2ExecutionResponse,\n executeV2Api,\n isApiV2ExecutionResponse,\n parseStreamResult,\n readJsonResponseWithLimit,\n readTextResponseWithLimit,\n ResponseSizeLimitError,\n} from \"./api-utils.js\";\nimport type { ExecuteV2ApiParams } from \"./api-utils.js\";\nimport { getInputsWithFileMetadata } from \"./file-utils.js\";\nimport { withTrailingSlash } from \"./url-utils.js\";\n\ntype ApiResult<T = any> = {\n data?: T;\n error?: string;\n};\n\ntype ApiCallContext = {\n apiId: string;\n apiName: string;\n path: string;\n inputs: Record<string, any>;\n options: SbApiRunOptions;\n callback?: () => Promise<unknown>;\n};\n\ntype InternalExecuteApiParams = {\n apiId: string;\n apiName: string;\n path: string;\n inputs: Record<string, any>;\n options: SbApiRunOptions;\n callId?: string;\n callback?: () => Promise<unknown>;\n isTestRun?: boolean;\n injectedCallerId?: string; // EDIT MODE ONLY\n};\n\nconst ENVIRONMENT_ALL = \"*\";\n\nexport function getFetchByPathViewMode(\n appMode: AppMode | undefined,\n editMode: boolean,\n): OrchestratorViewMode {\n if (appMode === AppMode.PREVIEW) {\n return OrchestratorViewMode.PREVIEW;\n }\n\n if (appMode === AppMode.PUBLISHED) {\n return OrchestratorViewMode.DEPLOYED;\n }\n\n if (appMode === AppMode.EDIT) {\n return OrchestratorViewMode.EDIT;\n }\n\n // Some embedded apps strip Superblocks-owned URL params during client-side\n // navigation; a production build with missing app_mode should still execute\n // as deployed rather than requiring edit-mode permissions.\n return editMode ? OrchestratorViewMode.EDIT : OrchestratorViewMode.DEPLOYED;\n}\n\n/**\n * Local equivalent of the parent's `isProfileSupported` utility.\n * Determines whether an agent supports a given profile based on\n * its tags and legacy environment field.\n */\nfunction isAgentProfileSupported(\n agent: AgentInfo,\n targetEnvironment: string,\n): boolean {\n const supportedProfiles = agent.tags?.profile ?? [];\n\n // Wildcard: agent supports all profiles\n if (supportedProfiles.includes(ENVIRONMENT_ALL)) {\n return true;\n }\n\n // No profile tags: fall back to legacy environment field\n if (supportedProfiles.length === 0) {\n return (\n agent.environment === ENVIRONMENT_ALL ||\n agent.environment === targetEnvironment\n );\n }\n\n return supportedProfiles.includes(targetEnvironment);\n}\n\nclass ApiManager {\n /**\n * Pre-filtered agent URLs for the current profile, sent by the parent.\n * Used as fallback for cloud orgs where URLs come from\n * SUPERBLOCKS_UI_AGENT_BASE_URL rather than agent metadata.\n */\n private _agentUrls: string[] = [];\n /**\n * Full on-premise agent metadata (all profiles) from the parent,\n * enabling local profile-based filtering without a postMessage\n * round-trip. Empty for cloud orgs.\n */\n private _agents: AgentInfo[] = [];\n /**\n * DP routing config mapping profile keys to DP URLs, sent by the parent.\n * Only populated when dataPlaneGatewayEnabled is true.\n */\n private _dpRoutingConfig: Record<string, string> = {};\n private token: string | undefined;\n private accessToken: string | undefined;\n private runningApiControllers: Record<string, Set<AbortController>> = {};\n private waitForInitApiPromise: Promise<void> | undefined = undefined;\n private waitForBootstrapPromise: Promise<void> | undefined = undefined;\n private resolveBootstrapPromise: (() => void) | undefined = undefined;\n // Store call contexts for re-running APIs from the editor\n private callContexts: Record<string, ApiCallContext> = {};\n\n /**\n * Flush pending file writes to DBFS, logging a warning if it blocks for\n * >50ms. Returns the elapsed time in ms so callers can record it in the\n * execution timing breakdown.\n */\n private async timedEnsureFilesSynced(label: string): Promise<number> {\n const opManager = this.rootStore.editStore?.operationManager;\n if (!opManager) return 0;\n const t0 = performance.now();\n await opManager.ensureFilesSynced();\n const ms = Math.round(performance.now() - t0);\n if (ms > 50) {\n console.warn(\n `[api-store] ensureFilesSynced blocked ${label} for ${String(ms)}ms`,\n );\n }\n return ms;\n }\n\n constructor(readonly rootStore: RootStore) {\n this.waitForBootstrapPromise = new Promise((resolve) => {\n this.resolveBootstrapPromise = resolve;\n });\n }\n\n set agentUrls(urls: string[]) {\n this._agentUrls = urls;\n }\n\n set agents(agents: AgentInfo[]) {\n this._agents = agents;\n }\n\n set dpRoutingConfig(config: Record<string, string>) {\n this._dpRoutingConfig = config;\n }\n\n setTokens(token: string, accessToken: string) {\n this.token = token;\n this.accessToken = accessToken;\n }\n\n clearTokens() {\n this.token = undefined;\n this.accessToken = undefined;\n }\n\n isInitialized() {\n return !!this.token && !!this.accessToken;\n }\n\n /**\n * Get agent URLs for the given profile by filtering locally stored\n * agent metadata. Falls back to the pre-filtered `_agentUrls` when\n * no full agent metadata is available (cloud orgs or legacy parents).\n */\n private getAgentUrlsForProfile(profileKey: string): string[] {\n if (this._agents.length > 0) {\n return this._agents\n .filter((agent) => isAgentProfileSupported(agent, profileKey))\n .map((agent) => agent.url);\n }\n // Fallback: pre-filtered URLs (cloud orgs or older parent shells)\n return this._agentUrls;\n }\n\n /**\n * Selects a random agent URL from the available agents and returns it normalized\n * (with trailing slash) to ensure proper URL path joining.\n */\n private getRandomAgentBaseUrl(profileKey: string): string | undefined {\n const urls = this.getAgentUrlsForProfile(profileKey);\n if (!urls.length) {\n return undefined;\n }\n const agentUrl = urls[Math.floor(Math.random() * urls.length)];\n return withTrailingSlash(agentUrl);\n }\n\n private async awaitInitApiIfNeeded() {\n if (this.waitForInitApiPromise) {\n await this.waitForInitApiPromise;\n }\n }\n\n private async awaitBootstrapIfNeeded() {\n if (this.waitForBootstrapPromise) {\n console.debug(\"[api-store] Waiting for bootstrap to complete...\");\n await this.waitForBootstrapPromise;\n console.debug(\"[api-store] Bootstrap complete, proceeding.\");\n }\n }\n\n notifyBootstrapComplete() {\n if (this.resolveBootstrapPromise) {\n this.resolveBootstrapPromise();\n }\n\n // Pre-warm discovery + file sync so the first API execution after\n // bootstrap (e.g. useApi on component mount) doesn't block on them.\n void this.prewarmExecutionPath();\n }\n\n private async prewarmExecutionPath(): Promise<void> {\n try {\n await this.rootStore.awaitDiscovery();\n await this.rootStore.editStore?.operationManager.ensureFilesSynced();\n } catch {\n // Best-effort — execution path will retry if this fails.\n }\n }\n\n loadApiManifest({\n apis = {},\n }: {\n apis?: Record<string, { api: DeleteMeLibraryApi; scopeId: string }>;\n }) {\n const entries = Object.values(apis);\n const apisToSet: Array<DeleteMeLibraryApi & { scopeId: string }> =\n entries.map(({ api, scopeId }) => {\n api.apiPb.metadata.id = api.apiPb.metadata.name; // TODO get rid of this once SABS is updated\n return {\n ...api,\n scopeId,\n };\n });\n\n const waitForInitApiPromise = new Promise((resolve) => {\n const callbackId = addNewPromise(resolve);\n window.parent.postMessage(\n {\n type: \"set-apis-deployed-mode\",\n payload: {\n apis: apisToSet,\n callbackId,\n },\n },\n \"*\",\n );\n });\n\n this.waitForInitApiPromise = waitForInitApiPromise as Promise<void>;\n }\n\n @action\n async rerunApiByCallId(callId: string): Promise<ApiResult> {\n const context = this.callContexts[callId];\n if (!context) {\n console.error(`No call context found for callId: ${callId}`);\n throw new Error(`No call context found for callId: ${callId}`);\n }\n\n // If a callback is available, invoke it to trigger the original state updates\n // The callback will internally call runApiByPath with the same callId and callback\n if (context.callback) {\n await context.callback();\n return { data: undefined, error: undefined };\n }\n\n // Fallback to direct execution if no callback\n // Pass the original callId so we don't create a new run record\n const result = await this.executeApi({\n apiId: context.apiId,\n apiName: context.apiName,\n path: context.path,\n inputs: context.inputs,\n options: context.options,\n callId, // Reuse the same callId\n callback: undefined, // No callback for fallback execution\n });\n\n return { data: result.data, error: result.error };\n }\n\n @action\n async runApiByPath({\n path,\n inputs,\n callId,\n callback,\n isTestRun,\n injectedCallerId,\n }: {\n path: string;\n inputs: SbApiRunOptions;\n callId?: string;\n callback?: () => Promise<unknown>;\n isTestRun?: boolean;\n injectedCallerId?: string;\n }): Promise<ApiResult> {\n console.debug(\"[api-store.runApiByPath] Called with:\", {\n path,\n inputs,\n callId,\n isTestRun,\n hasCallback: !!callback,\n });\n\n await this.awaitInitApiIfNeeded();\n await this.awaitBootstrapIfNeeded();\n\n // take name on /apis/<name>/api.yaml (legacy) or /server/apis/<name>/api.ts (SDK)\n const apiName = path.match(\n /^\\/(?:server\\/)?apis\\/([^/]+)\\/api\\.(yaml|ts)$/,\n )?.[1];\n if (!apiName) {\n console.error(\"[api-store] Invalid path:\", path);\n throw new Error(`Invalid path: ${path}`);\n }\n\n console.debug(\"[api-store.runApiByPath] Extracted apiName:\", apiName);\n\n editorBridge.setApiStarted(apiName);\n\n console.debug(\"[api-store.runApiByPath] Executing API internally...\");\n\n const result = await this.executeApi({\n apiId: apiName,\n apiName,\n path,\n inputs: inputs,\n options: inputs ?? {},\n callId,\n isTestRun,\n callback,\n injectedCallerId,\n });\n\n console.debug(\n \"[api-store.runApiByPath] Execution complete, calling setApiResponse for:\",\n apiName,\n );\n editorBridge.setApiResponse(apiName, result.parsedResult);\n\n return { data: result.data, error: result.error };\n }\n\n private getHMRCallHash(params: InternalExecuteApiParams): string {\n return `${params.injectedCallerId ?? \"\"}-${params.apiId}`;\n }\n\n private getCachedHMRExecution(params: InternalExecuteApiParams): null | {\n parsedResult: ExecutionResponse | undefined;\n data: any;\n error: string | undefined;\n } {\n if (params.callId) {\n return null;\n }\n\n const hmrCallHash = this.getHMRCallHash(params);\n if (ApiHmrTracker.shouldSkipRun(hmrCallHash)) {\n const result = ApiHmrTracker.getCachedResult(hmrCallHash);\n if (result) {\n return result as any;\n }\n }\n return null;\n }\n\n private async executeApi(params: InternalExecuteApiParams): Promise<{\n parsedResult: ExecutionResponse | undefined;\n data: any;\n error: string | undefined;\n }> {\n if (isEditMode()) {\n const cachedResult = this.getCachedHMRExecution(params);\n if (cachedResult) {\n console.debug(\"[api-store] Using cached result\", params);\n return cachedResult;\n }\n const result = await this.executeApiInternal(params);\n ApiHmrTracker.setResult(this.getHMRCallHash(params), result);\n return result;\n }\n\n return this.executeApiInternal(params);\n }\n\n private async executeApiInternal({\n apiId,\n apiName,\n path,\n inputs,\n options,\n callId: providedCallId,\n callback,\n isTestRun,\n }: InternalExecuteApiParams): Promise<{\n parsedResult: ExecutionResponse | undefined;\n data: any;\n error: string | undefined;\n }> {\n const executionStartTime = Date.now();\n const callId =\n providedCallId ??\n `${apiId}-${executionStartTime}-${Math.random().toString(36).substr(2, 9)}`;\n\n // If this is a re-run (callId already exists), set loading state\n const isRerun = !!this.callContexts[callId];\n if (isRerun) {\n editorBridge.updateApiRunRecord(apiId, callId, {\n loading: true,\n });\n }\n\n if (!this.rootStore.applicationId) {\n sendNotification({\n message:\n \"No application ID was found, ensure the app was bootstrap correctly.\",\n type: \"error\",\n });\n return {\n parsedResult: {\n status: \"STATUS_COMPLETED\",\n execution: \"\",\n errors: [\n {\n message:\n \"No application ID was found, ensure the app was bootstrap correctly.\",\n },\n ],\n },\n data: null,\n error: \"No application ID was found\",\n };\n }\n\n const profileKey = superblocksContext.profiles?.selected?.key ?? \"staging\";\n\n const agentBaseUrl = (() => {\n if (this.rootStore.dataPlaneGatewayEnabled) {\n const dpUrl = this._dpRoutingConfig[profileKey];\n if (dpUrl) {\n return withTrailingSlash(dpUrl);\n }\n // Fallback to CP URL when no DP mapping exists for this profile\n return this._agentUrls[0]\n ? withTrailingSlash(this._agentUrls[0])\n : this.getRandomAgentBaseUrl(profileKey);\n }\n return this.getRandomAgentBaseUrl(profileKey);\n })();\n if (!agentBaseUrl) {\n sendNotification({\n message: \"No active agent found\",\n type: \"error\",\n });\n return {\n parsedResult: {\n status: \"STATUS_COMPLETED\",\n execution: \"\",\n errors: [{ message: \"No active agent found\" }],\n },\n data: null,\n error: \"No active agent found\",\n };\n }\n\n const orchestratorUrl = new URL(\"v2/execute\", agentBaseUrl).href;\n const profileId = superblocksContext.profiles?.selected?.id ?? \"\";\n\n const events: Array<StreamEvent> = [];\n\n await this.timedEnsureFilesSynced(\"executeApi\");\n\n // Create abort controller for this API execution\n const abortController = new AbortController();\n (this.runningApiControllers[apiName] ??= new Set()).add(abortController);\n\n const editMode = isEditMode();\n\n // Determine the actual view mode for profile restrictions\n const appMode = getAppMode();\n const orchestratorViewMode = getFetchByPathViewMode(appMode, editMode);\n\n // TODO when we support streaming - this should come from the API config\n // Right now we only stream in edit mode in order to support the API editor\n const isStream = editMode ? true : false;\n\n const waitForAuthPromise = new Promise((resolve) => {\n const callbackId = addNewPromise(resolve);\n window.parent.postMessage(\n {\n type: \"authenticate-api-request\",\n payload: {\n ...(this.accessToken ? { accessToken: this.accessToken } : {}),\n apiId,\n callbackId,\n },\n },\n \"*\",\n );\n });\n const authResult: any = await waitForAuthPromise;\n if (authResult?.tokens?.token && authResult?.tokens?.accessToken) {\n this.setTokens(authResult.tokens.token, authResult.tokens.accessToken);\n }\n if (authResult?.errors && authResult.errors.length > 0) {\n console.warn(\n \"[api-store] API authentication failed\",\n apiName,\n authResult.errors,\n );\n this.runningApiControllers[apiName]?.delete(abortController);\n const errorMessage = (authResult.errors as Array<{ message: string }>)\n .map((e) => e.message)\n .join(\"; \");\n const authError = `Authentication failed: ${errorMessage}`;\n if (isRerun) {\n editorBridge.updateApiRunRecord(apiId, callId, {\n error: authError,\n loading: false,\n });\n }\n return {\n parsedResult: {\n status: \"STATUS_COMPLETED\" as const,\n execution: \"\",\n errors: authResult.errors,\n },\n data: null,\n error: authError,\n };\n }\n\n const { traceHeaders, ...restArgs } = options;\n\n const { inputs: finalInputs, files } = await getInputsWithFileMetadata({\n ...restArgs,\n ...inputs,\n });\n\n // Determine which commitId/branchName to send based on view mode:\n // - EDIT mode (1): send branchName=\"main\"\n // - PREVIEW mode (2): extract commitId from URL query params\n // - DEPLOYED mode (3): send branchName=\"main\" (orchestrator needs it to construct URL, server will ignore and lookup deployedCommitId)\n const fetchByPathParams: {\n path: string;\n applicationId: string;\n commitId?: string;\n branchName?: string;\n profile: { name: string; id: string };\n viewMode: OrchestratorViewMode;\n } = {\n path,\n applicationId: this.rootStore.applicationId ?? \"\",\n profile: {\n name: profileKey,\n id: profileId,\n },\n viewMode: orchestratorViewMode,\n };\n\n // Add commitId or branchName based on mode\n if (orchestratorViewMode === OrchestratorViewMode.EDIT) {\n // EDIT mode: use branch name\n fetchByPathParams.branchName = \"main\";\n } else if (orchestratorViewMode === OrchestratorViewMode.PREVIEW) {\n // PREVIEW mode: extract commitId from URL\n const urlParams = new URLSearchParams(window.location.search);\n const commitId = urlParams.get(\"commitId\");\n if (commitId) {\n fetchByPathParams.commitId = commitId;\n } else {\n fetchByPathParams.branchName = \"main\";\n }\n } else if (orchestratorViewMode === OrchestratorViewMode.DEPLOYED) {\n // DEPLOYED mode: send branchName so orchestrator knows what URL to call\n // Server will ignore it and lookup deployedCommitId based on viewMode=3\n fetchByPathParams.branchName = \"main\";\n }\n\n const syncResponse = await executeV2Api({\n body: {\n inputs: finalInputs,\n fetchByPath: fetchByPathParams,\n options: {\n includeEventOutputs: editMode,\n includeEvents: isStream || editMode,\n includeResolved: editMode,\n },\n },\n apiName,\n controlFlowOnlyFiles: files,\n environment: profileKey,\n eventType: \"api\",\n notifyOnSystemError: true,\n responseType: isStream ? ApiResponseType.STREAM : ApiResponseType.SYNC,\n baseUrl: isStream ? orchestratorUrl + \"/stream\" : orchestratorUrl,\n agents: [],\n viewMode: editMode ? ViewMode.EDITOR : ViewMode.DEPLOYED,\n accessToken: this.accessToken ?? \"\",\n token: this.token ?? \"\",\n maxResponseBytes:\n this.rootStore.orchestratorExecuteResponseSizeLimitBytes,\n traceHeaders: traceHeaders,\n abortController,\n onMessage: (message: any) => {\n editorBridge.sendStreamedApiMessage(message, apiName);\n },\n processStreamEvents: (event: StreamEvent) => {\n events.push(event);\n editorBridge.sendStreamedApiEvent(event, apiName);\n },\n } satisfies ExecuteV2ApiParams);\n\n const hasSystemError =\n syncResponse != null &&\n typeof syncResponse === \"object\" &&\n \"systemError\" in syncResponse;\n const parsedResult =\n (isStream\n ? hasSystemError\n ? syncResponse\n : (parseStreamResult(events, {\n includeFinalOutput: true,\n }) ?? syncResponse) // Fall back to syncResponse if stream had no events (e.g., early error)\n : syncResponse) ?? undefined;\n\n if (parsedResult) {\n decodeBytestringsInV2ExecutionResponse(parsedResult);\n }\n\n this.runningApiControllers[apiName]?.delete(abortController);\n\n const error = this.findError(parsedResult ?? undefined);\n const data = isApiV2ExecutionResponse(parsedResult)\n ? parsedResult?.output?.result\n : null;\n\n // Extract step logs from execution events\n const stepLogs = this.extractStepLogs(parsedResult);\n\n const executionEndTime = Date.now();\n const timeTaken = executionEndTime - executionStartTime;\n\n this.callContexts[callId] = {\n apiId,\n apiName,\n path,\n inputs,\n options,\n callback,\n };\n\n // Bound the response, inputs, and step logs captured into the editor run\n // record so a large payload can't exhaust the editor tab's memory. The app\n // still receives the full, untruncated `data` via the return below. Only do\n // this in edit mode -- outside the editor the run-record bridge is a no-op,\n // so skip the serialization cost on the deployed/preview hot path.\n //\n // Bounding is best-effort and must NEVER reject the run: the network fetch\n // already succeeded, so a defect in the bounding helpers must not deny the\n // app data it should have received. On any failure we omit the inspector\n // copy (rather than forward an unbounded payload that could OOM the editor).\n let boundedResponse: ReturnType<typeof boundRunRecordValue> = {\n value: data,\n truncated: false,\n };\n let boundedInputs: ReturnType<typeof boundRunRecordValue> = {\n value: inputs,\n truncated: false,\n };\n let boundedStepLogs: ReturnType<typeof boundRunRecordStepLogs> = {\n stepLogs,\n truncated: false,\n };\n if (editMode) {\n try {\n boundedResponse = boundRunRecordValue(data);\n boundedInputs = boundRunRecordValue(inputs);\n // A single-fetch API's terminal step output is the same object as\n // `data`; reuse the response bound instead of serializing it again.\n boundedStepLogs = boundRunRecordStepLogs(stepLogs, {\n value: data,\n bounded: boundedResponse,\n });\n } catch (err) {\n const omitted =\n \"[Superblocks editor: run record omitted -- inspector bounding failed. The full result is still available to your app.]\";\n console.warn(\n \"[api-store] editor run-record bounding failed; omitting inspector copy:\",\n err instanceof Error ? err.message : String(err),\n );\n boundedResponse = {\n value: omitted,\n truncated: true,\n reason: \"unserializable\",\n };\n boundedInputs = {\n value: omitted,\n truncated: true,\n reason: \"unserializable\",\n };\n boundedStepLogs = { stepLogs: undefined, truncated: true };\n }\n }\n // Use the bounded value, not raw `inputs`: when not truncated it is either\n // the original inputs (unchanged) or the JSON-safe sanitized form (BigInt /\n // circular), so the inspector's inputs pane never receives a value its\n // JSON.stringify render can't handle.\n const recordInputs = boundedInputs.truncated\n ? ({ superblocksTruncated: boundedInputs.value } as Record<string, any>)\n : (boundedInputs.value as typeof inputs);\n\n if (isRerun) {\n editorBridge.updateApiRunRecord(apiId, callId, {\n timestamp: executionStartTime,\n statusCode: this.extractStatusCode(parsedResult),\n timeTaken,\n inputs: recordInputs,\n inputsTruncated: boundedInputs.truncated,\n response: boundedResponse.value,\n responseTruncated: boundedResponse.truncated,\n error,\n loading: false,\n isTestRun,\n stepLogs: boundedStepLogs.stepLogs,\n stepLogsTruncated: boundedStepLogs.truncated,\n });\n } else {\n editorBridge.addApiRunRecord(apiId, {\n id: `${apiId}-${executionStartTime}`,\n callId,\n timestamp: executionStartTime,\n statusCode: this.extractStatusCode(parsedResult),\n timeTaken,\n inputs: recordInputs,\n inputsTruncated: boundedInputs.truncated,\n response: boundedResponse.value,\n responseTruncated: boundedResponse.truncated,\n error,\n loading: false,\n isTestRun,\n stepLogs: boundedStepLogs.stepLogs,\n stepLogsTruncated: boundedStepLogs.truncated,\n });\n }\n\n return { parsedResult, data, error };\n }\n\n private findError(apiResponse?: ExecutionResponse): string | undefined {\n if (apiResponse && \"systemError\" in apiResponse) {\n // For client errors (4xx), show the error message in run records\n // For server errors (5xx) or network errors, don't show in run records\n // (they're framework/infrastructure errors, not API business logic errors)\n const statusCode = apiResponse.statusCode ?? 500;\n if (statusCode >= 400 && statusCode < 500) {\n return apiResponse.systemError;\n }\n return undefined;\n }\n\n const firstUnhandledError = apiResponse?.errors?.find(\n (error) => !error?.handled,\n );\n\n if (!firstUnhandledError) {\n return undefined;\n }\n return `Error in API: ${firstUnhandledError?.message}`;\n }\n\n private extractStatusCode(response?: ExecutionResponse): number {\n if (!response) return 500;\n if (\"systemError\" in response) {\n // Use the actual HTTP status code if available, otherwise default to 500\n return response.statusCode ?? 500;\n }\n if (\"errors\" in response && response.errors && response.errors.length > 0) {\n // Check if the error has a status code in extensions (GraphQL-style errors)\n const firstError = response.errors[0];\n\n // Try structured fields first\n let statusCode =\n (firstError as any)?.extensions?.statusCode ??\n (firstError as any)?.extensions?.http?.status;\n\n // If not found, try parsing from the message string\n if (!statusCode && (firstError as any)?.message) {\n const message = (firstError as any).message as string;\n // Look for \"status code XXX\" pattern\n const match = message.match(/status code (\\d+)/i);\n if (match) {\n statusCode = parseInt(match[1], 10);\n }\n }\n\n if (statusCode) {\n return statusCode;\n }\n return 500;\n }\n if (\"status\" in response && response.status === \"STATUS_COMPLETED\")\n return 200;\n return 500;\n }\n\n /**\n * Extract step-level logs from execution events.\n * Captures console.log (stdout), console.error (stderr), output, and errors for each step.\n */\n private extractStepLogs(response?: ExecutionResponse): Array<{\n stepName: string;\n stdout?: string[];\n stderr?: string[];\n output?: unknown;\n error?: string;\n }> {\n if (!response || !isApiV2ExecutionResponse(response) || !response.events) {\n return [];\n }\n\n const stepLogs: Array<{\n stepName: string;\n stdout?: string[];\n stderr?: string[];\n output?: unknown;\n error?: string;\n }> = [];\n\n for (const event of response.events) {\n // Handle both ExecutionEvent and StreamEvent\n const execEvent: ExecutionEvent | undefined =\n \"result\" in event ? (event as StreamEvent).result.event : event;\n\n if (!execEvent?.end) continue;\n\n const { end, name } = execEvent;\n const hasLogs =\n (end.output?.stdout && end.output.stdout.length > 0) ||\n (end.output?.stderr && end.output.stderr.length > 0) ||\n end.output?.result !== undefined ||\n end.error?.message;\n\n if (hasLogs) {\n stepLogs.push({\n stepName: name,\n stdout: end.output?.stdout,\n stderr: end.output?.stderr,\n output: end.output?.result,\n error: end.error?.message,\n });\n }\n }\n\n return stepLogs;\n }\n\n /**\n * Execute an SDK API directly via the orchestrator's v3/execute endpoint.\n * Reads execution context (profile, branch, tokens) from rootStore so the\n * caller doesn't need to resolve them through the parent frame.\n */\n async executeSdkApiV3(\n apiName: string,\n inputs: Record<string, unknown>,\n options?: { signal?: AbortSignal },\n ): Promise<{\n success: boolean;\n output?: unknown;\n error?: { code: string; message: string };\n diagnostics?: unknown[];\n executionStartMs?: number;\n executionDurationMs?: number;\n fetchStartMs?: number;\n timingBreakdown?: ExecutionTimingBreakdown;\n }> {\n const timingT0 = performance.now();\n\n // Wait for the bootstrap response so commitId, applicationId, and auth\n // tokens are guaranteed to be populated. Without this, deployed-mode\n // requests can race against the async bootstrap message and omit\n // commitId, causing the server to require UPDATE permission instead of\n // VIEW — which fails for viewer-role users.\n await this.awaitBootstrapIfNeeded();\n const bootstrapMs = Math.round(performance.now() - timingT0);\n let authCheckMs = 0;\n let discoveryMs = 0;\n let fileSyncMs = 0;\n let networkMs: number | undefined;\n\n const buildTimingBreakdown = (): ExecutionTimingBreakdown => ({\n authCheckMs,\n bootstrapMs,\n discoveryMs,\n fileSyncMs,\n networkMs,\n });\n\n const applicationId = this.rootStore.applicationId;\n if (!applicationId) {\n return {\n success: false,\n error: { code: \"NO_APP_ID\", message: \"No application ID found\" },\n timingBreakdown: buildTimingBreakdown(),\n };\n }\n\n // Create an AbortController for this execution and register it so\n // cancelApi() can abort all in-flight SDK API requests for this name.\n // Concurrent calls are tracked independently — cancelApi() aborts all.\n const abortController = new AbortController();\n (this.runningApiControllers[apiName] ??= new Set()).add(abortController);\n\n // If the caller supplied an external signal (e.g. from a React cleanup),\n // forward its abort to our internal controller.\n const forwardAbort = () => abortController.abort();\n if (options?.signal) {\n if (options.signal.aborted) {\n abortController.abort();\n } else {\n options.signal.addEventListener(\"abort\", forwardAbort, { once: true });\n }\n }\n\n try {\n // Deployed mode pre-registers SDK API entry points from build-manifest.js,\n // so only wait for discovery when the entry point is still missing.\n let entryPoint = this.rootStore.getApiEntryPoint(apiName);\n if (!entryPoint) {\n const discoveryT0 = performance.now();\n await this.rootStore.awaitDiscovery();\n discoveryMs = Math.round(performance.now() - discoveryT0);\n if (discoveryMs > 50) {\n console.warn(\n `[api-store] awaitDiscovery blocked executeSdkApiV3(${apiName}) for ${String(discoveryMs)}ms`,\n );\n }\n entryPoint = this.rootStore.getApiEntryPoint(apiName);\n }\n\n // Clark / preview often calls a brand-new API after the last discovery\n // completed but before (or while) HMR rediscovery registers it. Join or\n // kick a rediscovery pass once before failing UNKNOWN_API.\n if (!entryPoint && this.rootStore.sdkApiEnabled) {\n try {\n const rediscoveryT0 = performance.now();\n const { discoverAndRegisterSdkApis } =\n await import(\"../sdk-api-discovery.js\");\n await discoverAndRegisterSdkApis();\n const rediscoveryMs = Math.round(performance.now() - rediscoveryT0);\n discoveryMs += rediscoveryMs;\n if (rediscoveryMs > 50) {\n console.warn(\n `[api-store] rediscovery blocked executeSdkApiV3(${apiName}) for ${String(rediscoveryMs)}ms`,\n );\n }\n entryPoint = this.rootStore.getApiEntryPoint(apiName);\n } catch (error) {\n // Keep the structured UNKNOWN_API path below — do not reject execute.\n console.error(\n `[api-store] rediscovery failed for executeSdkApiV3(${apiName}):`,\n error,\n );\n }\n }\n\n if (!entryPoint) {\n return {\n success: false,\n error: {\n code: \"UNKNOWN_API\",\n message: `No entryPoint registered for API \"${apiName}\". Was it discovered?`,\n },\n timingBreakdown: buildTimingBreakdown(),\n };\n }\n\n // Flush pending file writes to DBFS before execution so newly created\n // or modified SDK API files are available to the orchestrator.\n fileSyncMs = await this.timedEnsureFilesSynced(\n `executeSdkApiV3(${apiName})`,\n );\n\n const selectedProfile = superblocksContext.profiles?.selected;\n const requestProfile = selectedProfile\n ? {\n id: selectedProfile.id,\n name: selectedProfile.displayName,\n key: selectedProfile.key,\n }\n : this.rootStore.profile;\n const branchName = this.rootStore.branchName;\n const editModeBranchName = branchName ?? \"main\";\n const commitId = this.rootStore.commitId;\n const editMode = isEditMode();\n const appMode = getAppMode();\n const viewMode = editMode\n ? OrchestratorViewMode.EDIT\n : appMode === AppMode.PREVIEW\n ? OrchestratorViewMode.PREVIEW\n : OrchestratorViewMode.DEPLOYED;\n\n const profileKey = requestProfile?.key ?? \"default\";\n const agentBaseUrl = (() => {\n if (this.rootStore.dataPlaneGatewayEnabled) {\n const dpUrl = this._dpRoutingConfig[profileKey];\n if (dpUrl) {\n return withTrailingSlash(dpUrl);\n }\n // Fallback to CP URL when no DP mapping exists for this profile\n return this._agentUrls[0]\n ? withTrailingSlash(this._agentUrls[0])\n : this.getRandomAgentBaseUrl(profileKey);\n }\n return this.getRandomAgentBaseUrl(profileKey);\n })();\n if (!agentBaseUrl) {\n return {\n success: false,\n error: {\n code: \"NO_AGENT\",\n message: \"Unable to resolve agent for API execution\",\n },\n timingBreakdown: buildTimingBreakdown(),\n };\n }\n\n const { inputs: finalInputs, files } =\n await getInputsWithFileMetadata(inputs);\n\n const body: Record<string, unknown> = {\n applicationId,\n inputs: finalInputs,\n viewMode,\n entryPoint,\n };\n const exportName = this.rootStore.getApiExportName(apiName);\n if (exportName) {\n body.exportName = exportName;\n }\n if (files.length > 0) {\n body.files = files;\n }\n if (requestProfile) {\n body.profile = requestProfile;\n }\n if (editMode) {\n body.branchName = editModeBranchName;\n body.includeDiagnostics = true;\n }\n if (!editMode && commitId) {\n body.commitId = commitId;\n }\n\n const declaredIntegrations =\n this.rootStore.getApiIntegrations(apiName) ?? [];\n const integrationIds = declaredIntegrations.map(\n (integration) => integration.id,\n );\n\n // Always round-trip `authenticate-api-request` -- even for\n // integrationless SDK APIs -- so the parent (deployed embed shell or\n // legacy edit/preview parent) can refresh long-lived tokens before\n // `/v3/execute`. Without this, an embed left open longer than the\n // Auth0 token TTL would 401 every API call. The deployed shell's\n // resolver returns `{ tokens }` when no FE-auth is required.\n const authCheckT0 = performance.now();\n const authResult = await new Promise((resolve) => {\n const callbackId = addNewPromise(resolve);\n window.parent.postMessage(\n {\n type: \"authenticate-api-request\",\n payload: {\n ...(this.accessToken ? { accessToken: this.accessToken } : {}),\n apiId: apiName,\n callbackId,\n integrationIds,\n ...(requestProfile ? { profile: requestProfile } : {}),\n },\n },\n \"*\",\n );\n });\n authCheckMs = Math.round(performance.now() - authCheckT0);\n const authData = authResult as\n | {\n tokens?: { token: string; accessToken: string };\n errors?: Array<{ message: string }>;\n }\n | undefined;\n if (authData?.tokens?.token && authData?.tokens?.accessToken) {\n this.setTokens(authData.tokens.token, authData.tokens.accessToken);\n }\n if (authData?.errors?.length) {\n console.warn(\n \"[api-store] SDK API authentication failed\",\n apiName,\n authData.errors,\n );\n return {\n success: false,\n error: {\n code: \"AUTH_ERROR\",\n message: authData.errors.map((e) => e.message).join(\"; \"),\n },\n timingBreakdown: buildTimingBreakdown(),\n };\n }\n\n // `fetchStartMs` is exposed to the UI as a wall-clock timestamp so it\n // can be aligned with `Date.now()` measurements on the parent (e.g.\n // `execution.timestamp`). Use a separate monotonic marker for the\n // network-duration calculation to avoid NTP adjustments producing\n // negative deltas.\n const fetchStartMs = Date.now();\n const fetchPerfT0 = performance.now();\n const response = await fetch(`${agentBaseUrl}v3/execute`, {\n method: \"POST\",\n credentials: \"include\",\n headers: {\n \"Content-Type\": \"application/json\",\n [SUPERBLOCKS_AUTHORIZATION_HEADER]: `Bearer ${this.accessToken}`,\n Authorization: `Bearer ${this.token}`,\n [SUPERBLOCKS_REQUEST_ID_HEADER]: generateId(),\n },\n body: JSON.stringify(body),\n signal: abortController.signal,\n });\n\n if (!response.ok) {\n networkMs = Math.round(performance.now() - fetchPerfT0);\n const text = await readTextResponseWithLimit(\n response,\n this.rootStore.orchestratorExecuteResponseSizeLimitBytes,\n );\n let message: string;\n try {\n const json = JSON.parse(text);\n message =\n json?.responseMeta?.error?.message ??\n json?.error?.message ??\n json?.message ??\n text;\n } catch {\n message = text || `HTTP ${response.status}`;\n }\n // Reactive integration-auth signal: the orchestrator returns 401\n // when it has no auth record for a per-user integration and 403\n // when the record exists but the token is invalid/revoked. Both\n // are reauth cases for the host. We emit only when the API\n // declared integrations -- a 401 on an integrationless API is\n // about Superblocks bearer auth, not integration auth, and is\n // not actionable for the host.\n if (\n (response.status === 401 || response.status === 403) &&\n integrationIds.length > 0\n ) {\n embedStore.emitIntegrationAuthError({\n apiId: apiName,\n integrationIds,\n status: response.status,\n message,\n });\n }\n return {\n success: false,\n error: { code: \"SYSTEM_ERROR\", message },\n timingBreakdown: buildTimingBreakdown(),\n };\n }\n\n networkMs = Math.round(performance.now() - fetchPerfT0);\n const result = await readJsonResponseWithLimit(\n response,\n this.rootStore.orchestratorExecuteResponseSizeLimitBytes,\n );\n\n // Extract orchestrator-side execution timing when available.\n // The top-level `performance` field on AwaitResponse is not populated\n // for v3/execute, so fall back to the Event.End performance from the\n // events array (returned when view_mode is EDIT).\n // Guard against NaN so the downstream `?? timestamp` fallback works correctly.\n const eventPerf = (result.events as Array<Record<string, unknown>>)?.find(\n (e): e is Record<string, unknown> =>\n (e.end as Record<string, unknown> | undefined)?.performance != null,\n );\n const perf =\n result.performance ??\n (eventPerf?.end as Record<string, unknown> | undefined)?.performance;\n const perfObj = perf as { start?: number; total?: number } | undefined;\n const executionStartMs =\n perfObj?.start != null && Number.isFinite(Number(perfObj.start))\n ? Number(perfObj.start)\n : undefined;\n const executionDurationMs =\n perfObj?.total != null && Number.isFinite(Number(perfObj.total))\n ? Number(perfObj.total)\n : undefined;\n\n const timingBreakdown = buildTimingBreakdown();\n\n if (result.errors?.length) {\n return {\n success: false,\n error: {\n code: \"EXECUTION_ERROR\",\n message: result.errors[0].message,\n },\n diagnostics: result.diagnostics,\n executionStartMs,\n executionDurationMs,\n fetchStartMs,\n timingBreakdown,\n };\n }\n\n return {\n success: true,\n output: result.output?.result,\n diagnostics: result.diagnostics,\n executionStartMs,\n executionDurationMs,\n fetchStartMs,\n timingBreakdown,\n };\n } catch (error) {\n if (error instanceof ResponseSizeLimitError) {\n console.warn(\n \"[api-store] orchestrator /execute response size limit exceeded\",\n {\n apiName,\n applicationId,\n limitBytes: error.limitBytes,\n },\n );\n return {\n success: false,\n error: { code: \"SYSTEM_ERROR\", message: error.message },\n timingBreakdown: buildTimingBreakdown(),\n };\n }\n\n if (error instanceof Error && error.name === \"AbortError\") {\n return {\n success: false,\n error: {\n code: \"ABORTED\",\n message: `API \"${apiName}\" execution was aborted`,\n },\n timingBreakdown: buildTimingBreakdown(),\n };\n }\n console.error(\n `[api-store] executeSdkApiV3 failed for \"${apiName}\":`,\n error,\n );\n return {\n success: false,\n error: {\n code: \"NETWORK_ERROR\",\n message:\n error instanceof Error ? error.message : \"Network error occurred\",\n },\n timingBreakdown: buildTimingBreakdown(),\n };\n } finally {\n // Remove the external signal listener and clean up the controller\n // reference once the request settles.\n options?.signal?.removeEventListener(\"abort\", forwardAbort);\n this.runningApiControllers[apiName]?.delete(abortController);\n }\n }\n\n @action\n async cancelApi(apiName: string, _scopeId?: string) {\n const controllers = this.runningApiControllers[apiName];\n\n if (!controllers || controllers.size === 0) {\n console.warn(`No running API execution found for ${apiName}`);\n return;\n }\n\n // Abort all in-flight requests for this API name\n for (const c of controllers) {\n c.abort();\n }\n controllers.clear();\n\n // SDK APIs handle their own cancellation notification through the\n // abort signal → executeSdkApiV3 catch → useSdkApi \"sdk-api-execution-failed\".\n // Legacy APIs (v2, executeApiInternal) need the editorBridge notification\n // because their cancellation path doesn't send one otherwise.\n const isSdkApi =\n this.rootStore.sdkApiEnabled ||\n !!this.rootStore.getApiEntryPoint(apiName);\n if (!isSdkApi) {\n editorBridge.setApiResponse(apiName, {\n status: \"STATUS_CANCELLED\",\n execution: null,\n events: [],\n errors: [{ message: \"API execution was cancelled\" }],\n output: null,\n });\n }\n }\n}\n\nexport default ApiManager;\n","import { toJS } from \"mobx\";\n\nimport type { ScopedState } from \"@superblocksteam/library-shared/types\";\n\n// Cache for previous entity values to provide fallbacks when suspense is disabled\nconst objectFallbackCache = new WeakMap<object, Record<string, any>>();\n\nfunction sanitizeObject<T extends object>(obj: T): T {\n // Get or create fallback cache for this entity\n if (!objectFallbackCache.has(obj)) {\n objectFallbackCache.set(obj, {});\n }\n const fallbackCache = objectFallbackCache.get(obj)!;\n\n return new Proxy(obj, {\n get(target, prop) {\n try {\n const value = target[prop as keyof T];\n // Cache successful access for future fallback\n if (typeof prop === \"string\") {\n fallbackCache[prop] = value;\n }\n return value;\n } catch (error) {\n if (error instanceof Promise) {\n // Return cached value or undefined instead of throwing promise\n return typeof prop === \"string\" ? fallbackCache[prop] : undefined;\n }\n throw error;\n }\n },\n }) as T;\n}\n\nfunction sanitizeScopedState(state: ScopedState): ScopedState {\n return new Proxy(state, {\n get(target, prop) {\n const value = target[prop as keyof ScopedState];\n if (value && typeof value === \"object\" && \"type\" in value) {\n // This looks like an entity, sanitize it\n return sanitizeObject(value);\n }\n return value;\n },\n });\n}\n\nfunction sanitizedToJS<T>(value: T): T {\n if (value === null || value === undefined || typeof value !== \"object\") {\n return toJS(value);\n }\n return toJS(sanitizeObject(value));\n}\n\nexport { sanitizeObject, sanitizeScopedState, sanitizedToJS };\n","import diff, { type Difference } from \"microdiff\";\n\nimport { pathStringToArray } from \"@superblocksteam/library-shared\";\nimport type { MobXPatch } from \"@superblocksteam/library-shared/types\";\n\nimport { isReactElement } from \"../../lib/utils/clean-object.js\";\n\nexport const microPatches = (\n oldValue: any,\n newValue: any,\n baseStr: string,\n): MobXPatch[] => {\n const cleanedOldValue = removeBindAndReactElements(oldValue);\n const cleanedNewValue = removeBindAndReactElements(newValue);\n if (cleanedOldValue === undefined) {\n return [\n {\n op: \"add\",\n path: pathStringToArray(baseStr),\n value: cleanedNewValue,\n },\n ];\n }\n\n // Handle primitive value changes that microdiff can't handle (microdiff only supports arrays, objects and other builtins like Regex, Date, etc.)\n if (isPrimitive(cleanedOldValue) || isPrimitive(cleanedNewValue)) {\n if (cleanedOldValue !== cleanedNewValue) {\n return [\n {\n op: \"update\",\n path: pathStringToArray(baseStr),\n value: cleanedNewValue,\n } as const,\n ] satisfies MobXPatch[];\n }\n return []; // No change\n }\n\n const diffs = diff(cleanedOldValue, cleanedNewValue);\n const basePath = pathStringToArray(baseStr);\n return diffs.map((diff) => toMobXPatchFromMicroDiff(diff, basePath));\n};\n\nfunction isPrimitive(value: any): boolean {\n return (\n value === null ||\n typeof value === \"string\" ||\n typeof value === \"number\" ||\n typeof value === \"boolean\" ||\n typeof value === \"undefined\"\n );\n}\n\nfunction toMobXPatchFromMicroDiff(\n diff: Difference,\n basePath: (string | number)[],\n): MobXPatch {\n const type = diff.type;\n const fullPath = [...basePath, ...diff.path];\n\n switch (type) {\n case \"CREATE\":\n return {\n op: \"add\",\n path: fullPath,\n value: diff.value,\n } satisfies MobXPatch;\n case \"CHANGE\": {\n return {\n op: \"update\",\n path: fullPath,\n value: diff.value,\n } satisfies MobXPatch;\n }\n case \"REMOVE\":\n return {\n op: \"remove\",\n path: fullPath,\n } satisfies MobXPatch;\n default:\n throw new Error(`Unhandled diff type: ${type}`);\n }\n}\n\nconst removeBindAndReactElements = (value: any): any => {\n if (!value || typeof value !== \"object\") {\n return value;\n }\n if (isReactElement(value)) {\n return undefined;\n }\n if (Array.isArray(value)) {\n return value.map(removeBindAndReactElements);\n }\n return Object.fromEntries(\n Object.entries(value).map(([key, value]) => {\n if (key === \"bind\") {\n return [key, undefined];\n }\n return [key, removeBindAndReactElements(value)];\n }),\n );\n};\n","import {\n observe,\n isObservableMap,\n isObservableObject,\n isObservableArray,\n values,\n entries,\n} from \"mobx\";\nimport type { IObjectDidChange, IArrayDidChange, IMapDidChange } from \"mobx\";\n\nexport type IDisposer = () => void;\n\ntype IChange = IObjectDidChange | IArrayDidChange | IMapDidChange;\n\ntype Entry = {\n dispose: IDisposer;\n path: string;\n parent: Entry | undefined;\n};\n\ntype ObserveListener<T> = (change: IChange, path: string, root: T) => void;\n\nfunction buildPath(entry: Entry | undefined): string {\n if (!entry) return \"ROOT\";\n const res: string[] = [];\n while (entry.parent) {\n res.push(entry.path);\n entry = entry.parent;\n }\n return res.reverse().join(\"/\");\n}\n\nfunction isRecursivelyObservable(thing: any) {\n return (\n isObservableObject(thing) ||\n isObservableArray(thing) ||\n isObservableMap(thing)\n );\n}\n\n/**\n * Given an object, deeply observes the given object.\n * It is like `observe` from mobx, but applied recursively, including all future children.\n *\n * Note that the given object cannot ever contain cycles and should be a tree.\n *\n * As benefit: path and root will be provided in the callback, so the signature of the listener is\n * (change, path, root) => void\n *\n * The returned disposer can be invoked to clean up the listener\n *\n * deepObserve cannot be used on computed values.\n *\n * @example\n * const disposer = deepObserve(target, (change, path) => {\n * console.dir(change)\n * })\n */\nexport function deepObserve<T = any>(\n target: T,\n listener: ObserveListener<T>,\n): IDisposer {\n const entrySet = new WeakMap<any, Entry>();\n\n function genericListener(change: IChange) {\n const entry = entrySet.get(change.object)!;\n processChange(change, entry);\n listener(change, buildPath(entry), target);\n }\n\n function processChange(change: IChange, parent: Entry) {\n switch (change.type) {\n // Object changes\n case \"add\": // also for map\n observeRecursively(change.newValue, parent, change.name);\n break;\n case \"update\": // also for array and map\n unobserveRecursively(change.oldValue);\n observeRecursively(\n change.newValue,\n parent,\n (change as any).name || \"\" + (change as any).index,\n );\n break;\n case \"remove\": // object\n case \"delete\": // map\n unobserveRecursively(change.oldValue);\n break;\n // Array changes\n case \"splice\":\n change.removed.map(unobserveRecursively);\n change.added.forEach((value, idx) =>\n observeRecursively(value, parent, \"\" + (change.index + idx)),\n );\n // update paths\n for (\n let i = change.index + change.addedCount;\n i < change.object.length;\n i++\n ) {\n if (isRecursivelyObservable(change.object[i])) {\n const entry = entrySet.get(change.object[i]);\n if (entry) entry.path = \"\" + i;\n }\n }\n break;\n }\n }\n\n function observeRecursively(\n thing: any,\n parent: Entry | undefined,\n path: string,\n ) {\n if (isRecursivelyObservable(thing)) {\n const entry = entrySet.get(thing);\n if (entry) {\n if (entry.parent !== parent || entry.path !== path)\n // MWE: this constraint is artificial, and this tool could be made to work with cycles,\n // but it increases administration complexity, has tricky edge cases and the meaning of 'path'\n // would become less clear. So doesn't seem to be needed for now\n throw new Error(\n `The same observable object cannot appear twice in the same tree,` +\n ` trying to assign it to '${buildPath(parent)}/${path}',` +\n ` but it already exists at '${buildPath(entry.parent)}/${entry.path}'`,\n );\n } else {\n const entry = {\n parent,\n path,\n dispose: observe(thing, genericListener),\n };\n entrySet.set(thing, entry);\n entries(thing).forEach(([key, value]) =>\n observeRecursively(value, entry, \"\" + key),\n );\n }\n }\n }\n\n function unobserveRecursively(thing: any) {\n if (isRecursivelyObservable(thing)) {\n const entry = entrySet.get(thing);\n if (!entry) return;\n entrySet.delete(thing);\n entry.dispose();\n values(thing).forEach(unobserveRecursively);\n }\n }\n\n observeRecursively(target, undefined, \"\");\n\n return () => {\n unobserveRecursively(target);\n };\n}\n","import { pick } from \"lodash\";\nimport { isComputedProp, reaction } from \"mobx\";\nimport type { IReactionOptions } from \"mobx\";\n\nimport { toMobXPatch } from \"@superblocksteam/library-shared\";\nimport type { KeyToState } from \"@superblocksteam/library-shared/types\";\n\nimport { isEditMode } from \"../../lib/internal-details/is-edit-mode.js\";\nimport { sanitizedToJS } from \"../../lib/internal-details/lib/evaluator/sanitize-object.js\";\nimport { editorBridge } from \"../superblocks-editor-bridge.js\";\nimport { microPatches } from \"./create-patch.js\";\nimport { deepObserve } from \"./deep-observe.js\";\nimport type { IDisposer } from \"./deep-observe.js\";\n\ninterface MobXEditorSyncOptions<\n SID extends keyof KeyToState = keyof KeyToState,\n OUTPUT extends KeyToState[SID] = KeyToState[SID],\n STORE = OUTPUT,\n> {\n /* A unique identifier to ensure only the intended target receives these messages */\n storeId: SID & string;\n\n /* The observable store to sync (pass your data-only store) */\n store: STORE;\n\n /**\n * A function that takes the store and returns a view/projection of the store.\n * This is useful for syncing only a subset of the store in a different shape.\n */\n projection?: (store: STORE) => OUTPUT;\n\n /**\n * When provided, only patches under these keys are forwarded.\n * Other changes are dropped.\n */\n keys?: Record<keyof OUTPUT, true>;\n\n /**\n * Debounce time in milliseconds.\n */\n debounce?: number;\n}\n\n/**\n * Syncs a mobx store to the editor automatically through postmessage\n */\nexport function startEditorSync<\n SID extends keyof KeyToState = keyof KeyToState,\n OUTPUT extends KeyToState[SID] = KeyToState[SID],\n STORE = any,\n>(options: MobXEditorSyncOptions<SID, OUTPUT, STORE>): () => void {\n if (!isEditMode()) {\n return () => {};\n }\n\n const { store, storeId, keys, projection, debounce } = options;\n\n const reactionOptions: IReactionOptions<any, boolean> = {\n delay: debounce,\n name: `editor-sync(${storeId})`,\n };\n\n // Send the initial state to the editor\n let initialState: OUTPUT;\n if (keys) {\n const p = pick(store, Object.keys(keys));\n initialState = sanitizedToJS(p as unknown as OUTPUT);\n } else if (projection) {\n initialState = sanitizedToJS(projection(store));\n } else {\n initialState = sanitizedToJS(store as unknown as OUTPUT);\n }\n\n editorBridge.initializeEditorSyncedStore({\n storeId,\n initialState,\n });\n\n // Are we using selectors?\n if (projection) {\n // Re-evaluate projection for each key in each reaction:\n const initialProjection = projection(store);\n const projectionKeys = Object.keys(initialProjection);\n const createDisposer = (key: string) => {\n let lastValue: unknown;\n\n return reaction(\n () => {\n const currentProjection = projection(store);\n return sanitizedToJS(currentProjection[key as keyof OUTPUT]);\n },\n (value) => {\n const diffs = microPatches(lastValue, value, key);\n lastValue = value;\n const isSame = diffs.length === 0;\n if (!isSame) {\n editorBridge.updateEditorSyncedStore({\n storeId,\n patch: diffs,\n });\n }\n },\n reactionOptions,\n );\n };\n\n const projectionDisposers = projectionKeys.reduce(\n (acc, key) => {\n const disposer = createDisposer(key);\n acc[key] = disposer;\n return acc;\n },\n {} as Record<string, IDisposer>,\n );\n // add a disposer for the keys of the entire projection\n const projectionKeysDisposer = reaction(\n () => Object.keys(projection(store)),\n (newKeys: string[]) => {\n const lastKeys = Object.keys(projectionDisposers);\n const deletedKeys = lastKeys.filter((key) => !newKeys.includes(key));\n const addedKeys = newKeys.filter((key) => !lastKeys.includes(key));\n\n // Add new keys\n addedKeys.forEach((key) => {\n projectionDisposers[key] = createDisposer(key);\n // send an initial patch to the editor to create the key\n editorBridge.updateEditorSyncedStore({\n storeId,\n patch: {\n op: \"update\",\n path: [key],\n value: sanitizedToJS(projection(store)[key as keyof OUTPUT]),\n },\n });\n });\n\n // dispose of any keys that are no longer in the projection\n deletedKeys.forEach((key) => {\n projectionDisposers[key]();\n delete projectionDisposers[key];\n editorBridge.updateEditorSyncedStore({\n storeId,\n patch: {\n op: \"remove\",\n path: [key],\n },\n });\n });\n },\n reactionOptions,\n );\n return () => {\n projectionKeysDisposer();\n Object.values(projectionDisposers).forEach((disposer) => disposer());\n };\n }\n\n // Get all computed keys, as they are not observable by deepObserve\n const keyArr = Object.keys(keys ?? (store as any));\n const computedKeys = keyArr.filter((key) => isComputedProp(store, key));\n const observableKeys = keyArr.filter((key) => !computedKeys.includes(key));\n const disposers: IDisposer[] = [];\n // Create a reaction for each computed key\n const computedDisposers = computedKeys.map((key) =>\n reaction(\n () => store[key as keyof STORE],\n (value) => {\n editorBridge.updateEditorSyncedStore({\n storeId,\n patch: {\n op: \"update\",\n path: [key],\n value,\n },\n });\n },\n reactionOptions,\n ),\n );\n disposers.push(...computedDisposers);\n\n // We must deepObserve if there are non-computed keys,\n // We must also deepObserve if keys are NOT supplied, because new keys may be added\n const hasNonComputedKeys = observableKeys.length > 0;\n const userRestrictedToKeys = keys !== undefined;\n if (hasNonComputedKeys || !userRestrictedToKeys) {\n const deepDisposer = deepObserve(store, (change, pathStr) => {\n // Convert change to patch using utility function\n const patch = toMobXPatch(change, pathStr);\n if (keys && !keys[patch.path[0] as keyof OUTPUT]) {\n return;\n }\n\n // Post the patch along with the unique channelId.\n try {\n editorBridge.updateEditorSyncedStore({\n storeId,\n patch,\n });\n } catch (error) {\n console.error(\n `[startEditorSync][${storeId}] Failed to send patch:`,\n error,\n );\n }\n });\n disposers.push(deepDisposer);\n }\n\n return () => {\n disposers.forEach((disposer) => disposer());\n };\n}\n","import type { EntityDefinition } from \"@superblocksteam/library-shared/props\";\n\nimport type { ManagedProp } from \"../../../user-facing/properties-panel/props-builder\";\n\nexport const analyzePropertyType = (\n propData: ManagedProp,\n prop: any,\n): EntityDefinition[\"props\"][string][\"dataType\"] => {\n let dataType: EntityDefinition[\"props\"][string][\"dataType\"];\n\n if (\n propData.dataType === \"composite\" &&\n prop &&\n typeof prop.getProps === \"function\"\n ) {\n const nestedProps = prop.getProps();\n const objectFields: Record<string, any> = {};\n\n // Recursively analyze nested properties\n for (const [key, nestedProp] of Object.entries(nestedProps)) {\n if (nestedProp && typeof (nestedProp as any).build === \"function\") {\n const nestedPropData = (nestedProp as any).build();\n if (nestedPropData && nestedPropData.isExternallyReadable) {\n const nestedAnalysis = analyzePropertyType(\n nestedPropData,\n nestedProp,\n );\n objectFields[key] = nestedAnalysis;\n }\n }\n }\n\n // If we have readable nested properties, use the object structure as the dataType\n if (Object.keys(objectFields).length > 0) {\n dataType = objectFields;\n }\n } else if (propData.dataType === \"dimension\") {\n dataType = {\n mode: \"string\", // \"px\" | \"fit\" | \"fill\" | \"%\" | \"columns\" | \"rows\"\n value: \"number\", // Optional numeric value\n };\n } else if (\n propData.dataType === \"string\" ||\n propData.dataType === \"number\" ||\n propData.dataType === \"boolean\" ||\n propData.dataType === \"array\" ||\n propData.dataType === \"function\"\n ) {\n dataType =\n propData.dataType as EntityDefinition[\"props\"][string][\"dataType\"];\n } else {\n dataType = \"unknown\";\n }\n\n return dataType;\n};\n","import { makeAutoObservable } from \"mobx\";\nimport type * as React from \"react\";\n\nimport type { EntityDefinition } from \"@superblocksteam/library-shared/props\";\nimport type {\n ComponentRegistryShareState,\n CatalogWithInternalDetails,\n EditorConfig,\n} from \"@superblocksteam/library-shared/types\";\n\nimport { startEditorSync } from \"../../../../edit-mode/mobx-sync/mobx-editor-sync.js\";\nimport { RECORD_PATH_IDENTIFIER } from \"../../../user-facing/properties-panel/create-managed-props-list.js\";\nimport type {\n ManagedPropsList,\n PropertiesDefinition,\n Prop,\n} from \"../../../user-facing/properties-panel/props-builder.js\";\nimport type { EditorTemplate } from \"../../sb-wrapper.jsx\";\nimport type { RootStore } from \"../root-store.js\";\nimport { analyzePropertyType } from \"./type-defs-utils.js\";\n\nexport type DefaultTagNames = {\n container: string;\n button: string;\n text: string;\n};\n\n/**\n * Metadata stored for each registered component\n */\ntype ComponentMetadata = {\n type: string;\n propertiesDefinition: PropertiesDefinition;\n managedProps: ManagedPropsList;\n internalProps: Array<{ path: string; factory: () => any }>;\n editorTemplates: Array<EditorTemplate<any>>;\n editorConfig?: EditorConfig;\n};\n\n/**\n * TODO: The component registry could be split into two a thin layer always on, and move some stuff to the EditStore.\n * Some of the actions (rename, delete) and some of the data (isDroppable) are editor-only.\n */\nexport class ComponentRegistry implements ComponentRegistryShareState {\n // Primary registry: component type name (e.g., \"Badge\") -> all metadata\n // This is the main lookup path since most operations start with the type string\n private _componentRegistry = new Map<string, ComponentMetadata>();\n\n // Reverse index: raw component function -> component type name\n // Used only for component identity checking (isSbComponent)\n private _componentToType = new WeakMap<React.ComponentType<any>, string>();\n\n private _defaultContainerType: string | undefined;\n private _defaultButtonType: string | undefined;\n private _defaultTextType: string | undefined;\n\n constructor(readonly rootStore: RootStore) {\n makeAutoObservable(this);\n\n startEditorSync({\n store: this,\n storeId: \"component-registry\",\n keys: {\n customComponentList: true,\n libraryComponentCatalogs: true,\n libraryComponentEditorConfigs: true,\n entityDefinitions: true,\n },\n });\n }\n\n private getOrCreateMetadata(type: string): ComponentMetadata {\n let metadata = this._componentRegistry.get(type);\n if (!metadata) {\n metadata = {\n type,\n propertiesDefinition: {} as PropertiesDefinition,\n managedProps: [],\n internalProps: [],\n editorTemplates: [],\n editorConfig: undefined,\n };\n this._componentRegistry.set(type, metadata);\n }\n return metadata;\n }\n\n addComponent(\n type: string,\n rawComponent: React.ElementType,\n propertiesDefinition: PropertiesDefinition,\n ) {\n const metadata = this.getOrCreateMetadata(type);\n metadata.propertiesDefinition = propertiesDefinition;\n\n // Only add to WeakMap if it's a component reference (not a string)\n if (typeof rawComponent !== \"string\") {\n this._componentToType.set(rawComponent, type);\n }\n }\n\n deleteComponent(type: string) {\n this._componentRegistry.delete(type);\n }\n\n renameComponent(oldName: string, newName: string) {\n const metadata = this._componentRegistry.get(oldName);\n if (metadata) {\n metadata.type = newName;\n this._componentRegistry.set(newName, metadata);\n this._componentRegistry.delete(oldName);\n }\n }\n\n addManagedProps(type: string, props: ManagedPropsList) {\n const metadata = this.getOrCreateMetadata(type);\n metadata.managedProps = props;\n }\n\n deleteManagedProps(type: string) {\n const metadata = this.getOrCreateMetadata(type);\n metadata.managedProps = [];\n }\n\n addEditorTemplate(type: string, template: EditorTemplate<any>) {\n const metadata = this.getOrCreateMetadata(type);\n const existingTemplates = metadata.editorTemplates;\n if (\n existingTemplates.some(\n (t) =>\n t.catalog?.displayName === template.catalog?.displayName &&\n t.catalog?.category === template.catalog?.category,\n )\n ) {\n return;\n }\n metadata.editorTemplates = [...existingTemplates, template];\n }\n\n getEditorTemplates(type: string) {\n return this._componentRegistry.get(type)?.editorTemplates;\n }\n\n getEditorConfigFromComponentType(type: any) {\n const componentStrType = this.getTypeForComponent(type);\n return componentStrType\n ? this.getEditorConfig(componentStrType)\n : undefined;\n }\n\n addEditorConfig(type: string, config: EditorConfig) {\n if (config.useAs) {\n if (config.useAs.defaultContainer) {\n this._defaultContainerType = type;\n }\n if (config.useAs.defaultButton) {\n this._defaultButtonType = type;\n }\n if (config.useAs.defaultText) {\n this._defaultTextType = type;\n }\n }\n\n const metadata = this.getOrCreateMetadata(type);\n metadata.editorConfig = config;\n }\n\n addInternalProps(\n type: string,\n props: Array<{ path: string; factory: () => any }>,\n ) {\n const metadata = this.getOrCreateMetadata(type);\n metadata.internalProps = props;\n }\n\n getInternalProps(type: string): Array<{ path: string; factory: () => any }> {\n return this._componentRegistry.get(type)?.internalProps ?? [];\n }\n\n getEditorConfig(type: string) {\n return this._componentRegistry.get(type)?.editorConfig;\n }\n\n get entityDefinitions(): Record<string, EntityDefinition> {\n const entityDefinitions: Record<string, EntityDefinition> = {};\n\n for (const [componentType, metadata] of this._componentRegistry.entries()) {\n const propertiesDefinition = metadata.propertiesDefinition;\n if (!propertiesDefinition) {\n continue;\n }\n\n const entityDefinition: EntityDefinition = {\n description: metadata.editorConfig?.description,\n props: {},\n };\n for (const section of Object.values(propertiesDefinition)) {\n for (const [propKey, propValue] of Object.entries(section.props)) {\n if (!propValue) continue;\n const prop = propValue as Prop<any, any>;\n const propData = prop.build();\n if (propData && propData.isExternallyReadable) {\n const dataType = analyzePropertyType(propData, prop);\n\n const entityDefEntry: EntityDefinition[\"props\"][string] = {\n label: propData.docs?.label,\n description: propData.docs?.description,\n isSettable: propData.isExternallySettable,\n dataType,\n };\n\n entityDefinition.props[propKey] = entityDefEntry;\n }\n }\n }\n\n entityDefinitions[componentType] = entityDefinition;\n }\n\n return entityDefinitions;\n }\n\n get libraryComponentCatalogs() {\n const catalogs: Array<CatalogWithInternalDetails> = [];\n\n for (const [componentType, metadata] of this._componentRegistry.entries()) {\n for (const template of metadata.editorTemplates) {\n const catalog = template.catalog;\n if (catalog) {\n catalogs.push({\n ...catalog,\n componentType,\n });\n }\n }\n }\n\n return catalogs;\n }\n\n get libraryComponentEditorConfigs() {\n const configs: Record<string, EditorConfig> = {};\n\n for (const [componentType, metadata] of this._componentRegistry.entries()) {\n if (metadata.editorConfig) {\n configs[componentType] = metadata.editorConfig;\n }\n }\n\n return configs;\n }\n\n get customComponentList(): string[] {\n return Array.from(this._componentRegistry.keys());\n }\n\n get containerTypes() {\n // TODO - if we support more of these, add them here\n return new Set([this.defaultTagNames.container]);\n }\n\n get defaultTagNames(): DefaultTagNames {\n if (!this._defaultContainerType) {\n console.warn(\n \"No default container registered - defaulting to 'Container'.\",\n );\n }\n if (!this._defaultButtonType) {\n console.warn(\"No default button registered - defaulting to 'Button'.\");\n }\n if (!this._defaultTextType) {\n console.warn(\"No default text registered - defaulting to 'Text'.\");\n }\n return {\n container: this._defaultContainerType ?? \"Container\",\n button: this._defaultButtonType ?? \"Button\",\n text: this._defaultTextType ?? \"Text\",\n };\n }\n\n get managedPropsRegistry() {\n const registry = new Map<string, ManagedPropsList>();\n for (const [type, metadata] of this._componentRegistry.entries()) {\n registry.set(type, metadata.managedProps);\n }\n return registry;\n }\n\n getManagedProps(type: string): ManagedPropsList {\n return this._componentRegistry.get(type)?.managedProps ?? [];\n }\n\n /**\n * Get the component type string for a raw component reference.\n * Used for registry-based component identity checking.\n */\n getTypeForComponent(component: React.ComponentType<any>): string | undefined {\n return this._componentToType.get(component);\n }\n\n /**\n * Check if a component or element type is registered in the component registry.\n * Accepts both component references and string element names (e.g., \"div\").\n * Used for component identity checking instead of symbol-based approach.\n */\n hasComponent(component: React.ElementType | string): boolean {\n if (typeof component === \"string\") {\n // String element like \"div\" - check the main registry\n return this._componentRegistry.has(component);\n }\n // Component reference - check the WeakMap\n return this._componentToType.has(component);\n }\n\n /**\n * Get the property path with the record identifier if it exists. For example,\n * `columns.columnName.label` becomes `columns.*.label`, for record properties.\n */\n getPropertyWithRecordIdentifier(type: string, path: string) {\n const managedProps = this.getManagedProps(type);\n const splitPath = path.split(\".\");\n if (splitPath.length === 1) {\n return path;\n }\n const [parentKey, _maybeTheRecordKey, ...rest] = splitPath;\n\n for (const prop of managedProps) {\n // we don't always have a managed prop for the parent, only leafs\n if (\n prop.path.startsWith(parentKey) &&\n prop.path.includes(RECORD_PATH_IDENTIFIER) &&\n rest.length > 0 &&\n prop.path.endsWith(rest.join(\".\"))\n ) {\n return [parentKey, RECORD_PATH_IDENTIFIER, rest.join(\".\")].join(\".\");\n }\n }\n return path;\n }\n}\n","import { action, makeObservable } from \"mobx\";\nimport { observable } from \"mobx\";\n\nimport type { IntegrationDeclaration } from \"@superblocksteam/sdk-api\";\n\nimport type { EditStore } from \"../../../edit-mode/edit-store.js\";\nimport { LocationStore } from \"../location-store.js\";\nimport ApiManager from \"./features/api-store.js\";\nimport { ComponentRegistry } from \"./features/component-registry.js\";\nimport type { SdkProfileInfo } from \"./types.js\";\n\nexport const ORCHESTRATOR_EXECUTE_RESPONSE_SIZE_LIMIT_FLAG =\n \"orchestrator.execute.response-size-limit.bytes\";\n\n/**\n * User information extracted from JWT for SDK API execution.\n * Matches the ApiUser interface from @superblocksteam/sdk-api.\n */\nexport interface SdkApiUser {\n /** Unique user identifier from JWT */\n readonly userId: string;\n /** User's email address (if available) */\n readonly email?: string;\n /** User's display name (if available) */\n readonly name?: string;\n /** User's group memberships from JWT */\n readonly groups: string[];\n /** Custom claims from JWT */\n readonly customClaims: Readonly<Record<string, unknown>>;\n}\n\n/**\n * Default user object for when no user info is available.\n */\nconst DEFAULT_SDK_USER: SdkApiUser = {\n userId: \"anonymous\",\n groups: [],\n customClaims: {},\n};\n\nclass RootStore {\n apis: ApiManager;\n componentRegistry: ComponentRegistry;\n\n editStore?: EditStore;\n locationStore: LocationStore;\n\n currentPageScopeId: string | undefined;\n applicationId: string | undefined;\n userId: string | undefined;\n\n windowOriginUrl: string | undefined;\n\n /**\n * Current user info for SDK API execution.\n * Populated from JWT claims when available.\n */\n sdkUser: SdkApiUser = DEFAULT_SDK_USER;\n\n /**\n * Whether the SDK API feature is enabled.\n * Derived from the application's templateName (see `isSdkApiTemplate()`).\n * Passed to the library via the `clark.sdk-api.enabled` bootstrap flag.\n * When false, the YAML-based API system is used instead.\n */\n sdkApiEnabled = false;\n\n /**\n * Whether execute requests should be routed through the data plane gateway\n * endpoint instead of direct agent URLs.\n * Passed to the library via the ui.data-plane-gateway.enabled bootstrap flag.\n */\n dataPlaneGatewayEnabled = false;\n\n orchestratorExecuteResponseSizeLimitBytes: number | undefined;\n\n /** Selected integration profile for orchestrator API calls */\n profile: SdkProfileInfo | undefined;\n\n /** Current git branch name for editor-mode API execution */\n branchName: string | undefined;\n\n /** Deployed/preview commit ID for non-editor API execution */\n commitId: string | undefined;\n\n /**\n * Maps API name → entryPoint path (relative to app root).\n * Populated by sdk-api-discovery during edit mode.\n * Used by executeSdkApiV3 to resolve the correct file path for the orchestrator.\n */\n apiEntryPoints: Map<string, string> = new Map();\n\n /**\n * Maps API name → original export name in the source file.\n * Set for named exports (e.g. `export const GetUsers = api({...})`).\n * Undefined/absent for default exports.\n * Used by executeSdkApiV3 to send the correct `exportName` to the orchestrator.\n */\n apiExportNames: Map<string, string> = new Map();\n\n /**\n * Maps API name → statically declared integrations.\n * Populated during edit-mode discovery and from the deployed build manifest.\n */\n apiIntegrations: Map<string, IntegrationDeclaration[]> = new Map();\n\n /**\n * Resolves when the initial SDK API discovery pass completes.\n * executeSdkApiV3 awaits this so callers don't race against discovery.\n */\n private _discoveryPromise: Promise<void> | undefined;\n private _resolveDiscovery: (() => void) | undefined;\n\n private editorRegisteredCallbacks: (() => void)[] = [];\n\n constructor() {\n this.apis = new ApiManager(this);\n this.componentRegistry = new ComponentRegistry(this);\n\n this.locationStore = new LocationStore(this);\n\n makeObservable(this, {\n editStore: observable.shallow,\n setEditStore: action,\n\n applicationId: observable,\n userId: observable,\n sdkUser: observable.ref,\n setSdkUser: action,\n\n sdkApiEnabled: observable,\n setSdkApiEnabled: action,\n\n dataPlaneGatewayEnabled: observable,\n setDataPlaneGatewayEnabled: action,\n orchestratorExecuteResponseSizeLimitBytes: observable,\n setOrchestratorExecuteResponseSizeLimitBytes: action,\n\n profile: observable.ref,\n setProfile: action,\n branchName: observable,\n setBranchName: action,\n commitId: observable,\n setCommitId: action,\n });\n }\n\n /**\n * Updates the SDK user info from JWT claims or bootstrap data.\n */\n setSdkUser(user: Partial<SdkApiUser>) {\n this.sdkUser = {\n userId: user.userId ?? this.sdkUser.userId,\n email: user.email ?? this.sdkUser.email,\n name: user.name ?? this.sdkUser.name,\n groups: user.groups ?? this.sdkUser.groups,\n customClaims: user.customClaims ?? this.sdkUser.customClaims,\n };\n }\n\n /**\n * Sets the SDK API feature flag state.\n * Called during bootstrap with the value from feature flags.\n *\n * When enabling, pre-initializes the discovery gate immediately so that\n * any component whose useEffect runs before IframeConnected's reaction\n * useEffect (children run before parents in React) will correctly block\n * on awaitDiscovery() instead of resolving immediately with no entry points.\n */\n setSdkApiEnabled(enabled: boolean) {\n this.sdkApiEnabled = enabled;\n if (enabled && !this._resolveDiscovery) {\n this.initDiscoveryGate();\n }\n }\n\n setDataPlaneGatewayEnabled(enabled: boolean) {\n this.dataPlaneGatewayEnabled = enabled;\n }\n\n setOrchestratorExecuteResponseSizeLimitBytes(value: unknown) {\n const parsedValue =\n typeof value === \"number\"\n ? value\n : typeof value === \"string\" && value.trim() !== \"\"\n ? Number(value.trim())\n : undefined;\n\n this.orchestratorExecuteResponseSizeLimitBytes =\n typeof parsedValue === \"number\" &&\n Number.isFinite(parsedValue) &&\n parsedValue > 0\n ? Math.floor(parsedValue)\n : undefined;\n }\n\n setProfile(profile: SdkProfileInfo | undefined) {\n this.profile = profile;\n }\n\n setBranchName(branchName: string | undefined) {\n this.branchName = branchName;\n }\n\n setCommitId(commitId: string | undefined) {\n this.commitId = commitId;\n }\n\n setApiEntryPoint(apiName: string, entryPoint: string) {\n this.apiEntryPoints.set(apiName, entryPoint);\n }\n\n getApiEntryPoint(apiName: string): string | undefined {\n return this.apiEntryPoints.get(apiName);\n }\n\n setApiExportName(apiName: string, exportName: string) {\n this.apiExportNames.set(apiName, exportName);\n }\n\n getApiExportName(apiName: string): string | undefined {\n return this.apiExportNames.get(apiName);\n }\n\n clearApiEntryPoints() {\n this.apiEntryPoints.clear();\n this.apiExportNames.clear();\n }\n\n setApiIntegrations(apiName: string, integrations: IntegrationDeclaration[]) {\n this.apiIntegrations.set(apiName, integrations);\n }\n\n getApiIntegrations(apiName: string): IntegrationDeclaration[] | undefined {\n return this.apiIntegrations.get(apiName);\n }\n\n clearApiIntegrations() {\n this.apiIntegrations.clear();\n }\n\n /**\n * Initialise (or re-initialise) the discovery gate. Called when discovery\n * starts so that executeSdkApiV3 awaits before checking entry points.\n * Always creates a fresh promise so HMR re-discovery is also gated.\n * Resolves any in-flight promise before replacing it so callers awaiting\n * the old gate (e.g. from before HMR re-triggered discovery) do not hang.\n */\n initDiscoveryGate(): void {\n this._resolveDiscovery?.();\n this._discoveryPromise = new Promise<void>((resolve) => {\n this._resolveDiscovery = resolve;\n });\n }\n\n /**\n * Signal that the initial discovery pass has finished (success or failure).\n */\n notifyDiscoveryComplete(): void {\n this._resolveDiscovery?.();\n this._resolveDiscovery = undefined;\n }\n\n /**\n * Returns true if a discovery gate exists and has not yet been resolved.\n * Used by discoverAndRegisterSdkApis to avoid re-initializing the gate\n * when setSdkApiEnabled already pre-initialized it.\n */\n hasUnresolvedGate(): boolean {\n return !!this._resolveDiscovery;\n }\n\n /**\n * Returns a promise that resolves once initial discovery has completed.\n * Resolves immediately if discovery already finished or was never started.\n */\n awaitDiscovery(): Promise<void> {\n return this._discoveryPromise ?? Promise.resolve();\n }\n\n setEditStore(editStore: EditStore) {\n if (this.editStore) return;\n this.editStore = editStore;\n }\n\n notifyEditorRegistered() {\n this.editorRegisteredCallbacks.forEach((fn) => fn());\n this.editorRegisteredCallbacks = [];\n }\n\n // TODO: this is temporary until we have a method to ensure the editor is registered as soon as possible, i.e. before iframe messages\n onEditorRegistered(fn: () => void) {\n this.editorRegisteredCallbacks.push(fn);\n }\n}\n\nexport type { RootStore };\n\nexport default new RootStore();\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAOA,SAAgB,eAA0B;AACxC,KACE,CAAC,OAAO,+BACR,CAAC,OAAO,4BAA4B,cAEpC,OAAM,IAAI,MAAM,4BAA4B;AAE9C,QAAQ,OAAe;;;;ACNzB,SAAS,gCACP,UACA,gBAC2B;CAC3B,MAAM,cAAuD,EAAE;CAE/D,MAAM,sBACJ,iBACA,eACG;EACH,MAAM,aAA8C,EAAE;;;;;;;;;EAUtD,MAAM,oCACJ,MACA,aACoD;AACpD,OACE,EAAE,gBAAgB,kBAClB,CAAC,KAAK,2BAA2B,CAEjC,QAAO;GAGT,MAAM,cAAc,KAAK,oCAAoC;AAC7D,OAAI,CAAC,YACH,QAAO;AAQT,WAJE,OAAO,gBAAgB,aACnB,YAAY,gBAAgB,SAAS,GACrC,cAEsB,SAAS;;AAGvC,OAAK,MAAM,CAAC,MAAM,SAAS,OAAO,QAAQ,gBAAgB,EAAE;AAC1D,OAAI,CAAC,KAAM;GACX,MAAM,WAAW,aAAa,GAAG,WAAW,GAAG,SAAS;AAExD,OAAI,iCAAiC,MAAM,SAAS,EAAE;IAEpD,MAAM,uBAAuB,mBAC3B,KAAK,aACL,SACD;AACD,eAAW,KAAK,GAAG,qBAAqB;cAC/B,KAAK,2BAA2B,EAAE;IAO3C,MAAM,MAAM,KAAK,QAAQ,SAAS,CAAC,aAAa,eAAe;AAC/D,QAAI,IACF,YAAW,KAAK,IAAI;;;AAK1B,SAAO;;AAGT,MAAK,MAAM,WAAW,OAAO,OAAO,SAAS,EAAE;EAC7C,MAAM,WAAW,mBAAmB,QAAQ,OAAO,GAAG;AACtD,MAAI,SAAS,WAAW,EACtB;AAEF,cAAY,KAAK;GACf,MAAM,QAAQ;GACd,UAAU,QAAQ;GAClB;GACA,YAAY,QAAQ,sBAA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